Introduction to algorithms-Part 2: heap sorting

Source: Internet
Author: User

Heap sorting is very beautiful.AlgorithmAh, the first part describes insertion sorting, Merge Sorting, and implementation. Here there are two concepts: In-situ sorting (when sorting input arrays, only constant elements are put in a space outside the array); stable sorting (It is two equal numbers. The order before sorting is the same as that after sorting.)

Let's talk about this. Stable sorting includes Bubble sorting, insert sorting, Merge Sorting, and base sorting.Unstable sorting: Select sorting, fast sorting, shell sorting, and heap sorting. Insert sorting, Merge Sorting, heap sorting, and quick sorting are both relatively sorted (shell is regarded as periodic insertion ).

Sequence statistics (p72) also mentioned here ). Description: On a set composed of N numbers, the I-th sequence is the I-th smallest number in the set.

Is a heap. First, parent [I], left [I], and right [I] are introduced to represent the parent node of I and the Left and Right subnodes respectively. Core three steps of heap sorting: 1) Let a [I] Drop in the largest heap, and make the subtree with the root of I into a big top heap; 2) Build a heap, create the current array as a large or small top heap. Note that during the heap creation, the value ranges from length/2 to 0, because the root is in the length/2 range, in addition, the sequence value has a small impact, so you have to decrease the number (Exercise 6.3-2); 3) for heap sorting.

The core of heap sorting is to build a heap and put the largest element in the root position, that is, V [0], and then exchange v0 with the last element, create a heap for the remaining elements and get the current maximum value continuously. The process can be seen as recursion. So we can get the three stepsThe implementation is as follows:

 void maxheapify (vector 
  
    & V, int I) {// Let a [I] Drop in the max heap, make the subtree with I as the root into a big top heap int left = 2 * I + 1; // L <-left (I), where I starts from 0, so left and right are slightly different from pseudo 
    Code  In int right = 2 * I + 2; // R <-Right (I) int largest = I; If (left 
   
     V [I]) largest = left; else largest = I; If (right 
    
      V [Largest]) largest = right; // find the largest if (L Argest! = I) {swap (V [I], V [Largest]); // exchange enables the I and sub-heap to satisfy the heap nature, but the largest is the root of the vulnerability, recursively adjust maxheapify (v, largest) ;}} void buildheap (vector 
     
       & V) {// heap creation for (INT I = v. size ()/2; I> = 0; I --) maxheapify (V, I);} void heapsort (vector 
      
        & V) {// heap sorting vector 
       
         temp (V); V. clear (); buildheap (temp); // build temp into a large top heap for (INT I = temp. size ()-1; I> = 0; I --) {// record the heap top and the unsorted subsequence [0 .. swap (temp [0], temp [I]); V. push_back (temp [I]); // in this way, the V is bigger than temp. pop_back (); maxheapify (temp, 0); // set V [0 .. i-1] Reset to Big Top heap }}
       
      
     
    
   
  

For this heapsort process, because the pseudo code contains the size-1 Process of array A, but for V, we need to save all values and output them. Here we introduce the temporary array temp, use the temp pop_back to implement size-1, fit the pseudo code as much as possible, re-Add the sorting result through clear and push_back of V, and save the sorting result. The problem is that V is sorted from large to small. Of course, the array in pseudo code ranges from 1 to length. If you want to make left = 2 * I instead of 2 * I + 1, you can

 
V. insert (V. Begin (), int_max );

Insert a value at 0, but do not use it. However, this is of little significance.

In addition, do not ignore the pseudo code During Heap building: Heap-size [a] <-length [A]. This is different, although it is not obvious in the code, however, the two concepts must be differentiated.

Another solution for size-1 is to implement the following code when passing parameters:

Void maxheapify (vector <int> & V, int I, int size) // here the size is the current size {// Let a [I] Drop in the maximum heap, make the subtree with I as the root into a big top heap int left = 2 * I + 1; // L <-left (I) int right = 2 * I + 2; // R <-Right (I) int largest = I; If (left <size) & (V [left]> V [I]) // The result of comparison is sizelargest = left; else largest = I; If (right <= size) & (V [right]> V [Largest]) largest = right; // find the largest if (largest! = I) {swap (V [I], V [Largest]); // exchange enables the I and sub-heap to satisfy the heap nature, but the largest is the root of the vulnerability, recursively adjust maxheapify (v, largest, size) ;}} void buildheap (vector <int> & V) {// create heap for (INT I = v. size ()/2; I> = 0; I --) maxheapify (V, I, V. size ()-1);} void heapsort (vector <int> & V) {buildheap (V); cout <"V [0]: "<V [0] <Endl; cout <" Size: "<v. size () <Endl; cout <V [v. size ()-1] <Endl; For (INT I = v. size ()-1; I> 0; I --) {swap (V [0], V [I]); maxheapify (v, 0, I-1 ); // transmit the I-1 to achieve size-1, then V does not move }}

Of course, for the first step of the adjustment process, we can also eliminate recursion as follows:

 
Void maxheapify (vector <int> & V, int I, int size) {// Let a [I] Drop in the maximum heap, make the subtree with I as the root into a large top heap int Max, temp = V [I]; for (max = 2 * I; max <= size; Max * = 2) {// filter if (max <size & V [Max] <V [Max + 1]) Max ++ along the child node with a large key; if (temp> = V [Max]) break; V [I] = V [Max]; I = max;} V [I] = temp ;}

The above method does not require recursion. It is also the method in the book of Yan Weimin's data structure.

To sum up, the speed is second only to the speed of the heap sorting test. I have to say that it is still very powerful. The following is a priority queue.


Keep going...

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.