Kids Learn data structure (11): Heap Sort

Source: Internet
Author: User
Tags rounds

Kids Learn data structure (11): Heap Sort (a) what is a heap

The heap is actually a completely binary tree, with any one of its non-leaf nodes satisfying the nature:
KEY[I]<=KEY[2I+1]&&KEY[I]<=KEY[2I+2] or
KEY[I]>=KEY[2I+1]&&KEY>=KEY[2I+2],
That is, any non-leaf node keyword is not greater than or less than the key of the child node.
The heap is divided into large top piles and small top heaps, satisfying key[i]>=key[2i+1]&&key>=key[2i+2] called large top heaps, satisfying key[i]<=key[2i+1]&&key[i]<= KEY[2I+2] called the small top heap. By the above-mentioned properties, it is known that the key word of the heap top of the big Top heap is the largest of all the keywords, and the top of the heap of the small top heap is the smallest keyword in all the keywords.

(ii) The idea of heap sequencing

The use of large top heap (small top heap) heap top record is the maximum keyword (minimum keyword) This feature, making it easy to select the maximum record (minimum record) from the disorder every time.
Taking the big top pile as an example, its basic idea is:
A) The initial order to sort the keyword sequence (r1,r2 .... Rn) is constructed into a large top heap, which is the initial disordered zone;
b) Swap the top element of the heap r[1] with the last element R[n] to get a new unordered area (R1,R2,...... RN-1) and the new ordered area (Rn), and satisfies the r[1,2...n-1]<=r[n];
c) Since the exchange of new heap top r[1] may violate the nature of the heap, it is necessary to adjust the current unordered zone (r1,r2,......,rn-1) to a new heap, and then re-r[1] with the last element of the unordered area, to get a new unordered area (R1,R2 ...). Rn-2) and the new ordered area (RN-1,RN). This process is repeated until the number of elements in the ordered area is n-1, and the entire sorting process is complete.

(iii) Operation process

A) Initialize the heap: R[1..N] is constructed as a heap;
b) Swap the top element of the current unordered area R[1] with the last record of the interval, and then adjust the new unordered area to the new heap.
So for heap sequencing, the most important two operations are to construct the initial heap and adjust the heap, in fact, the construction of the initial heap is actually the process of adjusting the heap, but the initial heap is to construct all the non-leaf nodes are adjusted.

(iv) Examples and codes

For the two-step process, let's take the Shaping array a[]={16,7,3,20,17,8} as an example.
A) The first step is to construct the initial heap:
First, a complete binary tree is constructed based on the array element, which gets

4-1.jpg

Then you need to construct the initial heap, then start the adjustment from the last non-leaf node, and the adjustment process is as follows:


4-2.jpg 4-3.jpg

4-4.jpg
Because the 16,7,17 three nodes do not satisfy the nature of the heap, they need to be re-adjusted such as:

4-5.jpg

This will get the initial heap.
The above process is actually each adjustment from the parent node, left child node, right child node three of the largest selection of the parent node to exchange, after the exchange may cause the exchange of children nodes do not meet the nature of the heap, so after each exchange to re-exchange the child node to adjust.
The implementation code for the entire process is as follows:

#Include<stdio.h>voidHeapadjust(int *a,int I,int size)Adjust Heap {If I is a leaf node, no adjustment is necessary.if (I >= size/2) {Return }I non-leaf node, start adjustmentint lchild =2 * i +1;I's left child node numberint rchild =2 * i +2;I's right child node numberint max = i;Temp variableif (Lchild < size && A[lchild] > A[max]) {max = Lchild;}if (Rchild < size && A[rchild] > A[max]) {max = Rchild;}if (max! = i) {Convert a[i] and A[max] to a[i] = A[i] ^ A[max]; A[max] = A[i] ^ A[max]; A[i] = A[i] ^ A[max];If the subtree with Max as the parent node is not a heap, then the Heapadjust (A, max, size) will be adjusted to the subtree. }}voidBuildheap(int *a,int size) {Forint i = size/2-1; I >=0; i--)The maximum ordinal value of a non-leaf node is SIZE/2 {Heapadjust (A, I, size);}}IntMain(int argc,const char * argv[]) {int a[] = { Span class= "Hljs-number" >16, 7, 3,  17, 8}; int size = sizeof (a)/sizeof ( Span class= "Hljs-keyword" >int); Buildheap (A, size); //build heap printf ( "construct initial heap"); for (int i = 0; i < size; i++) {printf (return 0;}         

Operation Result:

构造出初始堆  20 17 8 7 16 3

b) Once you have the initial heap, you can sort

4-6.jpg

At this point 3 is not satisfied with the nature of the heap at the top of the heap need to continue tuning:

4-7.jpg

After adjustment, 3, 7, 16 This sub-heap does not meet the nature of the heap, continue to adjust:

4-8.jpg

So after the first round of adjustment, an ordered array of {20} and an adjusted heap are obtained. Continue with the following adjustments:

4-9.jpg 4-10.jpg 4-11.jpg

So after the second round of adjustment, an ordered array of {17,20} and an adjusted heap are obtained. Continue to adjust:

4-12.jpg 4-13.jpg

So after the third round of adjustment, an ordered array of {16,17,20} and an adjusted heap are obtained. Continue to adjust:

4-14.jpg 4-15.jpg

This way, after the fourth round of adjustment, an ordered array of {8,16,17,20} and an adjusted heap are obtained. Continue to adjust:

4-16.jpg

So after the fifth round of adjustment, we get an ordered array {7,8,16,17,20} and an adjusted heap, which has only one element and must be the smallest value in the entire array, so there is no need to adjust.
The above process shows that the total need to adjust 5 rounds, namely sizeof (array)-1 rounds.

The following code shows the implementation:

#Include<stdio.h>voidHeapadjust(int *a,int I,int size)Adjust Heap {If I is a leaf node, no adjustment is necessary.if (I >= size/2) {Return }I non-leaf node, start adjustmentint lchild =2 * i +1;I's left child node numberint rchild =2 * i +2;I's right child node numberint max = i;Temp variableif (Lchild < size && A[lchild] > A[max]) {max = Lchild;}if (Rchild < size && A[rchild] > A[max]) {max = Rchild;}if (max! = i) {Convert a[i] and A[max] to a[i] = A[i] ^ A[max]; A[max] = A[i] ^ A[max]; A[i] = A[i] ^ A[max];If the subtree with Max as the parent node is not a heap, then the Heapadjust (A, max, size) will be adjusted to the subtree. }}voidBuildheap(int *a,int size) {Forint i = size/2-1; I >=0; i--)The maximum ordinal value of a non-leaf node is SIZE/2 {Heapadjust (A, I, size);}}voidHeapsort(int *a,int size)Heap Sort {Buildheap (a, size);Forint i = size-1; i >0; i--) {Swaps the top of the heap and the last element, that is, each time the largest of the remaining elements is put to the last face a[i] = A[i] ^ a[0]; a[0] = a[i] ^ a[0]; A[i] = a[i] ^ a[0]; Heapadjust (A,0, I);Resize the top node of the heap to become a big Top heap}}IntMain(int argc,const char * argv[]) {int a[] = { Span class= "Hljs-number" >16, 7, 3,  17, 8}; int size = sizeof (a)/sizeof ( Span class= "Hljs-keyword" >int); Heapsort (A, size); //heap sort printf ( "heap-ordered results"); for (int i = 0; i < size; i++) { Span class= "hljs-built_in" >printf ( "%d", A[i]);} return 0;}         

Operation Result:

堆排序后的结果 3 7 8 16 17 20
(v) Further analysis

From the above process, the heap sort is also a sort of selection, a sort of tree selection. Just select the sort directly, in order to select the maximum record from R[1...N], you need to compare n-1 times, then select the maximum record from r[1...n-2] to compare n-2 times. In fact, many of these n-2 comparisons have already been made in the previous n-1 comparisons, and the tree-shaped selection sort happens to preserve some of the previous comparisons by using the tree shape feature, thus reducing the number of comparisons. For n keyword sequences, the worst case scenario is to compare LOG2 (n) times for each node, so the worst-case time complexity is nlogn. Heap sorting is an unstable sort and is not suitable for recording fewer sorts.



Kids Learn data structure (11): Heap Sort

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.