C + + implementation of heap sort (heap sort)

Source: Internet
Author: User
Tags sort

The heap sort contains two steps:

The first step: is to establish a large top heap (from large to small sort) or a small top heap (from little to large sort), from the bottom up; When the heap is built, S is from large to small;

The second step: is to switch the pile top and bottom, and the exchange of the bottom of the heap output, only arrange the remaining heap, from the top down to build; When constructed, S is always 1;

The time complexity of the heap sort (Heap sort) is O (Nlogn) and, at worst, the case.

And quick Sort, if the initial sequence of records is ordered, the quick sort will degenerate to bubble sort (Bubble sort), and the time complexity is O (n^2).

This is the advantage of heap sorting over a quick sort.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

Code:

* * * main.cpp * * Created on:2014.6.12 * author:spike//*eclipse CDT, gcc 4.8.1*/#incl  
      
Ude <iostream> #include <stack> #include <queue> using namespace std;  
    void Heapadjust (std::vector<int>& L, int s, int num) {int temp = l[s-1];  
        for (int j=2*s; j<=num; j*=2) {if (J<num && l[j-1] > L[j])//Select the smallest node location ++j;  
        if (temp < l[j-1])//Do not exchange break; L[S-1] = l[j-1]; Exchange value s = j;  
Continue to find} l[s-1] = temp;  
    } void Heapsort (std::vector<int>& L) {int num = l.size (); for (int i=num/2; i>0;-i) {heapadjust (L, I, num);//Build Heap from second layer} for (int i=num; i>1;  
        -i) {Std::swap (l[0], l[i-1]); Heapadjust (L, 1, i-1);  
Build the heap from the vertex, ignoring the last} return; int main (void) {std::vector<int> L ={49, 38, 65, 97, 76, 13, 27, 49};  
    Heapsort (L);  
    For (std::size_t i=0 i<l.size (); ++i) {std::cout << l[i] << "";  
    } std::cout << Std::endl;  
return 0; }

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.