[Common data structures - the stack (which is the time the buried)]

Brief introduction

  Heap (Heap) in computer science are collectively a special kind of data structure. Usually a heap can be seen as a complete binary array of objects.

  It is in line with a law, if the value of each root is larger than the value of all its child nodes, called large root heap, otherwise called the small heap root

 

Built heap

 First you have to have an array, and then we let it step by step in line with the rules of the heap (the large root heap)

First find the last non-leaf node (leaf node because no child nodes), and then step by step back to the root, to ensure that every root of the heap are smaller than its child nodes

1 for(int i=size/2-1;i>=0;--i)
2     make(a,i,size);

Then began to let them comply with the law

void the make ( int now, int size) 
{ 
        int left = 2 * + now . 1 ; // left son 
        int right = 2 * now + 2 ; // the right son 
        int max = now; // assuming he is the largest 
         // it compared with the child node, if the child node is greater than it,
         // order to maintain the stack law, we want now node maximum 
        IF (left <size && A [left]> A [max]) 
            max = left;
         IF (right <size && A [ right]> A [max]) 
            max = right; 
            
        IF(max =! now) 
        { 
            the swap (A [max], A [now]); 
            the make (max, size); // continues recursively down, because the switching node to small children, may not meet the rule of the heap 
        } 
}

Then one of the largest heap to built

Heapsort

Now, with a large root heap, but I want to sort, how to row it? First, at the top of this big pile of roots, these numbers must be the biggest, we just need to take out the biggest, then come back to maintain a large root heap, then remove the largest .......

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int a[100005],n;
 4 void make(int now,int size)
 5 {
 6     int left=2*now+1;
 7     int right=2*now+2;
 8     int max=now;
 9     if(left<size&&a[left]>a[max])
10         max=left;
11     if(right<size&&a[right]>a[max])
12         max=right;
13     if(max!=now)
14     {
15         swap(a[max],a[now]);
16         make(max,size);
17     }
18 }
19 
20 void heap_sort(int n)
21 {
22     for(int i=n/2-1;i>=0;--i)
23            make(i,n);
24     for(int i=n-1;i>=0;i--)
25     {
26         swap(a[0], a[i]);
27         cout<<a[i]<<" ";        
28         make(0,i);       
29     }
30 }
31  
32 int main()
33 {
34     cin>>n;
35     for(int i=0;i<n;i++)
36     {
37            scanf("%d",&a[i]);
38     }
39     heap_sort(n);
40     return 0;
41 }

Small heap sort root symbol to change it

 

Guess you like

Origin www.cnblogs.com/hualian/p/11348357.html