Heap sorting based on Sorting Algorithm Summary

Source: Internet
Author: User
Concept of heap.

N key word sequences KL, K2 ,..., Kn is called a heap, and only when the sequence meets the following properties (referred to as heap properties ):
(1) KI ≤ k2i and Ki ≤ k2i + 1 or (2) KI ≥ k2i and Ki ≥ k2i + 1 (1 ≤ I ≤)

Satisfying (1) is called a small root heap, and satisfying (2) is called a large root heap.
If we store the vector R [1 .. n] as a full binary tree storage structure, the heap is essentially a Complete Binary Tree that meets the following requirements: the keywords of any non-leaf node in the tree are not greater than (or not less) keywords of the left and right children (if any) nodes.

It can be found that the root node of the Big Top heap must be the largest node in the group of data values. That is to say, to sort a group of data, you only need to build this group into a big top heap first, the maximum value is selected.

Heap sorting thought:

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

The key to heap sorting is to build a heap. Follow these steps (large top heap ):

1) construct the sequence of initial keywords to be sorted (R1, R2.... RN) into a large top heap, which is the initial unordered zone;

2) swap the top element R [1] with the last element R [N] to obtain a new unordered zone (R1, R2 ,...... rn-1) and the new ordered zone (RN), and meet R [1, 2... n-1] <= R [N];

3) because the new heap top R [1] After switching may violate the heap nature, it is necessary for the current unordered zone (R1, R2 ,...... rn-1) adjusted to the new heap, and then re-exchange the R [1] with the last element of the unordered area, get the new unordered area (R1, R2 .... rn-2) and the new ordered zone (Rn-1, RN ). Repeat this process until the number of elements in the ordered area is n-1, the entire sorting process is completed.

Sorting Process

Through the above introduction, we can find that the heap sorting process is to repeat two steps:

1) initialize the heap: Create R [1. N] As a heap;

2) swap the top element R [1] In the unordered zone with the last record in the interval, and then adjust the unordered zone to the new heap.

Therefore, the two most important operations for heap sorting are the construction of the initial heap and the adjustment of the heap. In fact, the construction of the initial heap is also the process of adjusting the heap, however, when the initial heap is constructed, all non-leaf nodes are adjusted.

Heap creation (initialize heap)

The following is an example:

Heap sorts an integer array a [] = {16, 7, 3, 20, 17,8.

  • First, construct a Complete Binary Tree Based on the array element.

  • Then, you need to construct the initial heap and adjust it from the last non-leaf node, each adjustment is performed by selecting the parent node from the parent node, the left child node, and the right child node to exchange with the parent node (after the switch, the child node to be exchanged may not meet the nature of the heap, therefore, after each switch, you must re-adjust the child node to be switched ). The specific adjustment process is as follows:

After switching between 20 and 16, 16 does not meet the nature of the heap, so it needs to be adjusted again.

In this way, the initial heap is obtained.

Heap sorting

Swap the heap top element R [1] In the current unordered zone with the last record in the interval, and then adjust the new unordered zone to the new heap.

From the above process, we can see that heap sorting is actually a kind of selection sorting, and a kind of tree selection sorting. In order to directly select the sort... n] to select the maximum record, you need to compare n-1 times, and then from R [1... select the maximum record in N-2] to compare the N-2 times. In fact, many of the N-2 comparison has already done in the first n-1 comparison, and the tree selection and sorting just uses the characteristics of the tree to save some of the previous comparison results, so you can reduce the number of comparisons. For N keyword sequences, each node needs to compare log2 (n) times in the worst case. Therefore, the time complexity in the worst case is nlogn. The heap sorting is unstable and is not suitable for sorting with fewer records.

JAVA Implementation
Package COM. liuhao. sort; import Java. util. arrays; public class heapsort {public static void heapsort (datawrap [] data) {system. out. println ("start sorting"); int arraylen = data. length; // create heap cyclically for (INT I = 0; I <arraylen-1; I ++) {// create heap buildmaxheap (data, arraylen-1-I ); // swap (data, 0, arraylen-1-I); system. out. println (arrays. tostring (data ));}} /*** create a large top heap for the data array from 0 to lastindex ** @ Param data * @ Param lastindex */Private Static void buildmaxheap (datawrap [] data, int lastindex) {// start from the parent node of the node (last node) at lastindex for (INT I = (lastindex-1)/2; I> = 0; I --) {int K = I; // Save the node currently being determined. // if the child node of the current K node has a while (K * 2 + 1 <= lastindex) {int biggerindex = 2 * k + 1; // index of the Left subnode of the k node // If biggerindex <lastindex, it indicates that the K node has the right subnode, // compare the values of the left and right nodes, and place the larger index in biggerindexif (biggerindex <lastindex) {If (data [biggerindex]. compareto (data [biggerindex + 1]) <0) {biggerindex ++; // biggerindex always indicates the index of the larger subnode} // the value at the K node is smaller than the value of its subnode if (data [K]. compareto (data [biggerindex]) <0) {swap (data, K, biggerindex); // re-ensure that the value of K nodes is greater than that of its subnodes, it is mainly used to ensure that the subnode of K after switching meets the requirements of the Big Top heap K = biggerindex;} else {break ;}}}} /*** exchange the elements in the data array I and j indexes ** @ Param data * @ Param I * @ Param J */Private Static void swap (datawrap [] data, int I, Int J) {datawrap TMP = data [I]; data [I] = data [J]; data [J] = TMP ;} public static void main (string [] ARGs) {datawrap [] DATA = {New datawrap (21, ""), new datawrap (30, ""), new datawrap (49, ""), new datawrap (30, "*"), new datawrap (16, ""), new datawrap (9, "")}; system. out. println ("Before sorting:" + arrays. tostring (data); heapsort (data); system. out. println ("sorted:" + arrays. tostring (data ));}}
Sorting effect:

The key to heap sorting is the buildmaxheap () method. For the heap sorting of n data items, we need to build the heap for n-1 times. the time consumed for each heap is log2n, and the time efficiency is O (nlog2n ).

The heap sorting algorithm has a high space efficiency. Only one additional Program unit is required for exchange, and its space efficiency is O (1 ).

At the same time, heap sorting is unstable.

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

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.