Heap sorting heap Sort

Source: Internet
Author: User

Heap sorting is a sort of selection, with a time complexity of O (Nlogn).

Definition of a heap

The sequence of n elements, {k1,k2,...,kn}, is called a heap when and only if one of the following relationships is met.

Case 1:ki <= k2i and Ki <= k2i+1 ( minimized heap or small top heap )

Case 2:ki >= k2i and Ki >= k2i+1 ( largest heap or large top heap )

where i=1,2,..., n/2 downward rounding;

If a one-dimensional array corresponding to this sequence (that is, a storage structure with a one-dimensional array for this sequence) is treated as a complete binary tree , the meaning of the heap indicates that the values of all non-terminal nodes in the complete binary tree are not greater than (or not less than) the values of their left and right child nodes.

Thus, if the sequence {k1,k2,...,kn} is a heap, the top element of the heap (or the root of a complete binary tree) must be the minimum (or maximum) of n elements in the sequence.

For example, the following two sequence is a heap, corresponding to a complete binary tree

  

If after the minimum value of the top of the output heap, the sequence of the remaining n-1 elements is re-built into a heap, then the secondary small value of n elements is obtained. With this repeated execution, an ordered sequence can be obtained, a process called heap ordering .

Heap sort (heap sort) requires only one secondary space (for Exchange) that records the element size, and each record to be sorted occupies only one storage space.

Storage of Heaps

Generally use an array to represent the heap, the Joghen node exists ordinal 0, I node of the parent node subscript is (i-1)/2. The index of the left and right sub-nodes of the I node is 2*i+1 and 2*i+2 respectively.

(Note: If the root node is starting from 1, the left and right child nodes are 2i and 2i+1 respectively.) )

such as the No. 0 node of the left and right sub-nodes subscript 1 and 2 respectively.

As the maximized heap is as follows:

The left image is its storage structure, and the diagram on the right is its logical structure.

Implementation of Heap sorting

The implementation of heap sequencing requires two issues to be resolved:

1. How to build a heap from an unordered sequence?

2. How do I adjust the remaining elements to become a new heap after the top element of the output heap?

Consider the second problem, usually after the output heap top element, is considered to exclude this element, and then use the last element of the table to fill its position, from the top down to adjust: first, the heap of the topmost element and its left and right subtree of the root node to compare, the smallest elements exchanged to the top of the heap, and then along the path of the Until the leaves knot, you get a new heap.

We call this "screening" the adjustment process from the top of the heap to the leaves.

The process of building a heap from an unordered sequence is a process of "filtering" over and over again.

Constructing the initial heap

When the heap is initialized, all non-leaf nodes are screened.

The subscript for the last non-terminal element is [N/2] rounding down, so the filter only needs to start from [N/2] down to the entire element and adjust from the back to the next.

For example, given an array, a complete binary tree is constructed first based on the array element.

Then starting from the last non-leaf node, each time from the parent node, left child, right child to compare exchange, Exchange may cause the child node is not satisfied with the nature of the heap, so after each exchange need to re-exchange the child node to adjust.

To sort the heap

Once you have the initial heap, you can sort it out.

Heap sorting is a sort of selection. The initial heap is created as the initial unordered zone.

The sort begins with the first output of the heap top element (because it is the most valued), exchanging the top and last elements of the heap, so that the nth position (i.e. the last position) is the ordered area, the first n-1 position is still unordered, the unordered area is adjusted, the heap is obtained, and then the heap top and the last element are exchanged. This order area length becomes 2 ...

Do this continuously, resize the remaining elements to the heap, and then output the top elements of the heap to the ordered area. Each exchange results in an unordered area of 1, ordered area +1. Repeat this process until the ordered area length grows to n-1 and the sorting is complete.

Heap Sort Instance

First, build the initial heap structure

  

Then, swap the elements of the heap top and the last element, at this point the last position as an ordered area (the ordered area is shown in yellow), and then the other unordered area of the heap adjustment, after re-get the Big top heap, swap the top of the heap and the location of the second penultimate element ...

  

Repeat this process:

  

Finally, the order area extension is complete and the sorting is complete:

  

By the sorting process is visible, if you want to get ascending, then set up a large top heap, if you want to get descending, set up a small top heap .

Code

Assume that the ordered elements are integral, and that the element's keyword is itself.

Because it's going to be sorted in ascending order, use the Big Top heap.

The root node starts at 0, so the index of the left and right child nodes of the I node is 2i+1 and 2i+2.

Heap Sort//Heap Filter Functions//The definition of the heap is satisfied except for start in the known h[start~end]//This function is adjusted so that h[start~end] becomes a large top heaptypedefintElemtype;voidHeapadjust (Elemtype h[],intStartintend) {Elemtype temp=H[start];  for(inti =2*start +1; i<=end; i*=2)    {        //because the root node is assumed to be ordinal 0 instead of 1, I-node left child and right child are 2i+1 and 2i+2 respectively .        if(I<end && h[i]1])//The comparison between the left and right children        {            ++i;//I is the subscript for the larger record        }        if(Temp > H[i])//The comparison between the winner and father in the left and right children        {             Break; }        //The next round of screening is performed with the child's node position.h[start]=H[i]; Start=i; } H[start]= temp;//inserting elements that are initially discordant}voidHeapsort (Elemtype a[],intN) {    //build a big top pile first     for(inti=n/2; i>=0; --i) {heapadjust (a,i,n); }    //to sort     for(inti=n-1; I>0; --i) {//the last element and the first element are exchangedElemtype temp=A[i]; A[i]= a[0]; a[0] =temp; //then continue to adjust the remaining unordered elements to the big top heapHeapadjust (A,0. io1); }}
Heap sequencing analysis

Heap sorting method is not worth advocating for files with fewer records, but it is still very effective for n larger files. Because its run time is mainly spent on the initial heap under construction and the adjustment of the new heap when the repeated "filtering".

Heap sequencing in the worst case, the time complexity is also O (NLOGN). This is the greatest advantage of heap sorting relative to fast sorting. In addition, heap ordering requires only one record-size secondary storage space for Exchange.

Resources:

Min "Data Structure"

Http://www.cnblogs.com/dolphin0520/archive/2011/10/06/2199741.html

http://blog.csdn.net/morewindows/article/details/6709644

Heap sorting 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.