The maximum heap (binary) sorting is divided into several steps:
1.maxheap (), maintaining the nature of the maximum heap, that is, the value of the node is greater than the value of the child node, time complexity O (LGN)
2.bulid_max_heap (), constructs the largest heap from an unordered array, time complexity O (n)
3.heap_sort (), sorting unordered array, time complexity O (NLGN)
Code has comments
1#include <iostream>2 usingstd::cout;3 4 voidMax_heapify (int*a,intLeninti)5 {6 //array starting with 0, left child for 2i+1, right child for 2i+27 intL=2*i+1, r=2*i+2, largest;8 9 //Select the maximum value, record its pointer to largestTen if(L<len && a[l]>a[i]) largest=l; One Elselargest=i; A if(R<len && a[r]>a[largest]) largest=R; - if(largest!=i) - { the{inttemp=a[i];a[i]=a[largest];a[largest]=temp;} - - //The node is changed, so it is necessary to heapify the changed nodes. - //because Heapify is performed after its child node heapify. + max_heapify (a,len,largest); - } + } A voidBulid_max_heap (int*a,intlen) at { - //len/2,len/2+1 is a leaf node, not heapify . - for(inti=len/2; i>=0; i--) max_heapify (a,len,i); - } - voidHeapsort (int*a,intlen) - { in inttemp; - bulid_max_heap (A,len); to for(inti=len-1; i>=1; i--) + { - //Place the top of the heap (maximum) at the end of the array the{temp=a[0];a[0]=a[i];a[i]=temp;} * $ //the array length -1,heapify the root node and becomes the largest heapPanax Notoginsenglen--; -Max_heapify (A,len,0); the } + } A the + intMain () - { $ inta[]={ A,8564,445, About,8, Wu,6,4,5,4}; $Heapsort (A,Ten); - for(intI=0;i<Ten; i++) cout<<a[i]<<" "; - the return 0; -}
Sorting method Summary (i) heap sorting