PHP implements Heap Sort and heap

Source: Internet
Author: User

PHP implements Heap Sort and heap

Algorithm introduction:

Here I directly reference the beginning of "big talk Data Structure:

As mentioned above, simply select sorting. It needs to be compared n-1 times to select the smallest record among the n records to be sorted. This can also be understood, it is normal that the first data needs to be compared so many times; otherwise, how can we know that it is the smallest record.

Unfortunately, this operation does not save the comparison results of each trip. The comparison results of the next trip are heavy, and many of them have already been done in the previous one, however, because the comparison results are not saved in the previous sorting, the comparison operations are repeated in the next sorting, so the comparison times are recorded.

If you can select the minimum record and adjust other records based on the comparison results, the overall sorting efficiency will be very high. Heap sorting is an improvement of Simple selection and sorting, which is very effective.

Basic Idea:

Before introducing heap sorting, let's first introduce heap:

Definition in big talk Data Structure: heap is a Complete Binary Tree of the following nature: the value of each node is greater than or equal to the value of its left and right child nodes, A large top heap (a large root heap); or each node has a value smaller than or equal to the value of its left and right nodes, and becomes a small top heap (a small root heap ).

At that time, when I saw this, I also had a question about whether the heap is a Complete Binary Tree. On the Internet, I also said that the heap is not a complete binary tree, but I still keep my opinion on whether the heap is a Complete Binary Tree. As long as we know, here we use a full binary tree form of a large root heap (small heel heap), mainly to facilitate storage and computing (we will see the convenience later ).

Heap Sorting Algorithm:

Heap sorting is the method of sorting by heap (assuming a large root heap). Its basic idea is to construct the sequence to be sorted into a large root heap. At this time, the maximum value of the entire sequence is the root node on the top of the heap. Remove it (in fact, it is to swap it with the end element of the heap array, at this time the end element is the maximum value), and then re-construct the remaining n-1 series into a heap, in this way, the sub-small value of n elements is obtained. After repeated execution, an ordered sequence can be obtained.

Basic operations on the Sorting Algorithm of the big root heap:

① Heap Building: the heap building process is constantly adjusting the heap. from len/2 to the first node, len is the number of elements in the heap. The heap building process is a linear process. The heap adjustment process is called from len/2 to 0, which is equivalent to o (h1) + o (h2 )... + O (hlen/2) Where h Represents the depth of the node, and len/2 represents the number of nodes. This is a process of summation and the result is a linear O (n ).

② Adjust heap: the heap adjustment will be used in the heap building process and will also be used in the heap sorting process. The idea is to compare node I with its child node left (I), right (I), and select the three largest (or least), if the maximum (small) the value is not node I, but a child node of it. The interaction node I and the node over there, and then call the heap adjustment process, which is a recursive process. The time complexity of the heap adjustment process is related to the heap depth. It is an lgn operation because it is adjusted along the depth direction.

③ Heap sorting: the heap sorting is performed using the above two processes. First, build a heap based on the elements. Then remove the heap root node (usually exchange with the last node), the previous len-1 nodes continue the heap adjustment process, and then remove the root node, in this way, all nodes are retrieved. The time complexity of the heap sorting process is O (nlgn ). Because the time complexity of heap building is O (n) (once called), the time complexity of adjusting the heap is lgn, and n-1 times are called, therefore, the time complexity of heap sorting is O (nlgn ).

In this process, a large number of icons are required to understand, but I am lazy ......

Algorithm Implementation:

<? Php // heap sorting (improved sorting by simple selection) function swap (array & $ arr, $ a, $ B) {$ temp = $ arr [$ a]; $ arr [$ a] = $ arr [$ B]; $ arr [$ B] = $ temp;} // adjust the keywords of $ arr [$ start, make $ arr [$ start], $ arr [$ start + 1], and $ arr [$ end] a large root heap (the largest full Binary Tree of the root node) // note that the Left and Right nodes of s are 2 * s + 1 and 2 * s + 2 (when the array starts subscript is 0) function HeapAdjust (array & $ arr, $ start, $ end) {$ temp = $ arr [$ start]; // filter the child nodes with large keywords downward. // calculate the left and right children (I will use the array here to start the logo 0) // left child 2 * $ start + 1, right Child 2 * $ start + 2 for ($ j = 2 * $ Start + 1; $ j <= $ end; $ j = 2 * $ j + 1) {if ($ j! = $ End & $ arr [$ j] <$ arr [$ j + 1]) {$ j ++; // convert to right child} if ($ temp >=$ arr [$ j]) {break; // meet the requirements of the big root heap} // set the root node as the sub-node's greater $ arr [$ start] = $ arr [$ j]; // continue to $ start = $ j;} $ arr [$ start] = $ temp;} function HeapSort (array & $ arr) {$ count = count ($ arr ); // first construct the array into a large root heap (because it is a complete binary tree, so here we use floor ($ count/2)-1, nodes whose subscript is less than or equal to this number are all nodes with children.) for ($ I = floor ($ count/2)-1; $ I> = 0; $ I --) {HeapAdjust ($ arr, $ I, $ count) ;}for ($ I = $ count-1; $ I >=0; $ I --) {// swap the heap element with the last element, obtain the maximum element (the last element after the swap), and put the maximum element to the end of the array swap ($ arr, 0, $ I); // After switching, the last element (maximum element) is detached from the big root heap and the unordered new tree ($ arr [0... $ I-1]) retuned to the big root HeapAdjust ($ arr, 0, $ I-1) ;}$ arr = array (9, 1, 5, 8, 3, 7, 4, 6, 2 ); heapSort ($ arr); var_dump ($ arr );

Time Complexity Analysis:

As long as the running time is spent on the initial build pair and the repeated screening of the reconstruction heap.

In general, the time complexity of heap sorting is O (nlogn ). Because heap sorting is not sensitive to the sorting status of the original records, it is O (nlogn) regardless of the best, worst, and average time complexity ). The performance is obviously far better than the time complexity of bubble, simple selection, and direct insertion of O (n ^ 2.

Heap sorting is an unstable sorting method.

This blog is based on "big talk Data Structure" and is only recorded here for future reference!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.