Data Structure-heap sort and code (C ++)

Source: Internet
Author: User

Heap sort explanation and code (C ++)

 

Two steps are involved in heap sorting.:

Step 1:YesDading heap(Sorted in ascending order) orSmall top heap(Sorting from small to large ),Create from bottom up; For example, when a heap is created, s is from large to small;

Step 2:YesExchangeHeap top and heap bottom, andHeap bottom output after switching, Only arrange the remaining heap,Create from top down; For example, s is always 1 during construction;

 

Heap Sort)OfTime ComplexityYesO (nlogn),Worst caseThis is also true.

WhileQuick Sort)If the initial record sequence is ordered, the quick sorting degradesBubble Sort)The time complexity isO (n ^ 2).

This is a heap sorting method than quick sorting.Advantages.

 

Code:

 

/** Main. cpp ** Created on: 2014.6.12 * Author: Spike * // * eclipse cdt, gcc 4.8.1 */# include
 
  
# Include
  
   
# Include
   
    
Using namespace std; void HeapAdjust (std: vector
    
     
& L, int s, int num) {int temp = L [s-1]; for (int j = 2 * s; j <= num; j * = 2) {if (j
     
      
L [j]) // select the smallest node position + + j; if (temp <L [J-1]) // do not exchange break; L [s-1] = L [J-1]; // exchange value s = j; // continue searching} L [s-1] = temp;} void HeapSort (std: vector
      
        & L) {int num = L. size (); for (int I = num/2; I> 0; -- I) {HeapAdjust (L, I, num ); // build heap from Layer 2} for (int I = num; I> 1; -- I) {std: swap (L [0], L [I-1]); heapAdjust (L, 1, I-1); // build heap from vertex, ignore last} return;} int main (void) {std: vector
       
         L = {49, 38, 65, 97, 76, 13, 27, 49}; HeapSort (L); for (std: size_t I = 0; I
        
         

 

Output:

 

97 76 65 49 49 38 27 13 


 

 

 

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.