Heap sorting principle and algorithm implementation (maximum heap)

Source: Internet
Author: User

Heap Sort

Heap sorting is a sort of selection that takes advantage of the nature of the heap. Let's discuss the heap.

1. Heap

The heap is actually a completely binary tree, whatever a non-leaf node satisfies the nature:

KEY[I]<=KEY[2I+1]&&KEY[I]<=KEY[2I+2] or key[i]>=key[2i+1]&&key>=key[2i+2]

That is, no matter what a non-leaf node keyword is not greater than or not less than its left and right child node keyword.

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 clear that the top of the heap of the large top heap is the largest of all keyword, the keyword of the heap top of the keyword is the smallest of all keyword.

2. The idea of heap sequencing

The maximum keyword (minimum keyword) is recorded by the heap top of the large top heap (small top heap), making it easy to select the maximum record (minimum record) from the disorder each time.

Its basic idea is (Big Top heap):

1) the keyword sequence (r1,r2 ...) will be sorted initially. Rn) is constructed into a large top heap, which is the initial no-need zone;

2) 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];

3) because the new heap top r[1] may violate the nature of the heap, the current unordered zone (R1,R2,...... RN-1) adjusts to the new heap, then swaps the r[1] with the last element of the unordered zone, resulting in 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.

The procedure is as follows:

1) Initialize the heap: R[1..N] is constructed as a heap;

2) 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 the heap ordering, the most important two operations is to construct the initial heap and the adjustment heap, actually constructs the initial heap is actually adjusts the heap the process, only constructs the initial heap is to all non-leaf nodes to adjust.

The following examples illustrate:

Given an array of a[]={16,7,3,20,17,8}, it is sorted by heap.

First, a completely binary tree is constructed based on the array element, which gets

Then you need to construct the initial heap, then start with the last non-leaf node and adjust the steps such as the following:

20 and 16 after swapping causes 16 to not satisfy the nature of the heap, so it needs to be adjusted again

This will get the initial heap.

That is, each adjustment is from the parent node, the 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 the child node does not satisfy the nature of the heap, so each exchange after the exchange of children to adjust the node again). Once you have the initial heap, you are able to sort it out.

At this point 3 is in the heap top of the property of the heap, you need to adjust the continued adjustment

So the whole range is in order. From the above process, the heap sort is also a sort of selection, a sort of tree selection. Simply select the sort directly, in order to select the maximum record from R[1...N], it is more n-1 times, and then select the maximum record from r[1...n-2] to be n-2 times. In fact, this n-2 is very much in front of the n-1 is already done, and the tree-shaped selection of the tree-shaped choice of the characteristics of the use of the trees to save a portion of the previous comparison results, so can reduce the comparison of the number of times. For n keyword sequences, the worst case scenario for each node is log2 (n), so the worst-case time complexity is nlogn. Heap sorting is an unstable sort and is not suitable for recording fewer sorts. Test procedure
/*Heap sort (Big Top heap) 2011.9.14*/#include <iostream> #include <algorithm>using namespaceStdvoidHeapadjust (int*a,intIintSize//Adjustment Heap{intLchild=2*i;//I's left child node number    intRchild=2*i+1;//I's right child node number    intMax=i;//Temporary Variables    if(i<=size/2)//Assuming I is not a leaf node, there is no need to adjust{if(Lchild<=size&&a[lchild]>a[max])        {max=lchild; }if(Rchild<=size&&a[rchild]>a[max])        {max=rchild; }if(max!=i)            {swap (A[i],a[max]); Heapadjust (a,max,size);//avoid resizing a subtree with Max as the parent node is not a heap}    }        }voidBuildheap (int*a,intSize//Build Heap{intI for(i=size/2; i>=1; i--)//Non-leaf node maximum ordinal value is SIZE/2{heapadjust (a,i,size); }    }voidHeapsort (int*a,intSize//Heap Sort{intI Buildheap (a,size); for(i=size;i>=1; i--) {//cout<<a[1]<< "";Swap (a[1],a[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//buildheap (a,i-1); //set the remaining elements once again as a large top heapHeapadjust (A,1, I-1);//once again, the top node of the heap becomes the big top pile .}}intMainintargcChar*argv[]) {//int a[]={0,16,20,3,11,17,8};    inta[ -];intSize while(SCANF ("%d", &size) = =1&&size>0)    {intI for(i=1; i<=size;i++) cin>>a[i]; Heapsort (a,size); for(i=1; i<=size;i++) cout<<a[i]<<" ";    cout<<endl; }return 0;}

Heap sorting principle and algorithm implementation (maximum heap)

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.