**Heap sorting**And**Quick sorting**,**Merge Sorting**The same is a common sorting method with a time complexity of O (N * logn. Before learning about heap sorting, let's first explain what is a binary heap in the data structure.

Binary heap Definition

The binary heap is a complete binary tree or an approximate full binary tree.

The binary heap meets two features:

1. The key value of the parent node is always greater than or equal to (less than or equal to) the key value of any subnode.

2. The left and right subtree of each node are both a binary heap (both the maximum heap and the minimum heap ).

When the key value of the parent node is always greater than or equal to the key value of any child node**Max heap**. When the key value of the parent node is always less than or equal to the key value of any child node**Minimum heap**. Display a minimum heap:

Because there are few other heaps (such as the binary heap and the Fibonacci heap), the binary heap is generally referred to as the heap.

Heap Storage

Generally, the heap is represented by arrays. The subscript of the parent node of the I node is (I-1)/2. Its subnode subscript is 2 * I + 1 and 2 * I + 2 respectively. For example, the subnode subscripts of the first 0th nodes are 1 and 2 respectively.

Heap operation-insert and delete

The following describes how to create, insert, and delete the smallest heap in "Data Structure C ++ language description", and then provides the implementation code. It is best to first understand the diagram and then see the code.

Heap insertion

Each insert operation puts the new data at the end of the array. It can be found that from the parent node of the new data to the root node must be an ordered series. The current task is to insert the new data into this ordered data-this is similar**Insert sort directly**Merge a data into an ordered interval. It is not difficult to write the heap adjustment code when inserting a new data in comparison to "three implementations of directly inserting sorting in the vernacular classical algorithm series II:

// The parent node of the newly added I node is (I-1)/2 void minheapfixup (int A [], int I) {Int J, temp; temp = A [I]; j = (I-1)/2; // parent node while (j> = 0 & I! = 0) {if (a [J] <= temp) break; A [I] = A [J]; // move a large subnode down, replace its subnode I = J; j = (I-1)/2;} A [I] = temp ;}

The brief expression is as follows:

void MinHeapFixup(int a[], int i){ for (int j = (i - 1) / 2; (j >= 0 && i != 0)&& a[i] > a[j]; i = j, j = (i - 1) / 2) Swap(a[i], a[j]);}

Insert:

// Add new data nnumvoid minheapaddnumber (int A [], int N, int nnum) to the minimum heap {A [n] = nnum; minheapfixup (A, n );}

Delete heap

By definition, only 0th data records can be deleted at a time in the heap. To facilitate the reconstruction of the heap, the actual operation is to assign the value of the last data to the root node, and then make a top-down adjustment from the root node. When adjusting, first find the smallest node in the left and right son node. If the parent node is smaller than the smallest child node, it does not need to be adjusted. Otherwise, switch the parent node with it before considering the subsequent node. It is equivalent to a "sink" process of data from the root point. The following code is provided:

// Start from the I node, and N is the total number of nodes. From 0, the subnode of the I node is calculated as 2 * I + 1, 2 * I + 2 void minheapfixdown (int A [], int I, int N) {Int J, temp; temp = A [I]; j = 2 * I + 1; while (j <n) {If (J + 1 <n & A [J + 1] <A [J]) // find the smallest J ++ among left and right children; if (A [J]> = temp) break; A [I] = A [J]; // move a smaller subnode up, replace its parent node I = J; j = 2 * I + 1;} A [I] = temp ;} // Delete the number of void minheapdeletenumber (int A [], int N) {swap (A [0], a [n-1]); minheapfixdown (, 0, n-1 );}

Heap Array

With the heap insertion and deletion, consider how to perform the heap operation on a data. You need to retrieve data from the array one by one to create a heap. No! First look at an array, such:

Obviously, for the leaf node, it can be considered as a valid heap, that is, 20, 60, 65, 4, and 49 are both legal heap. You only need to start from a [4] = 50 and then adjust it downward. Then take a [3] = 30, a [2] = 17, a [1] = 12, a [0] = 9, and perform the downward adjustment operation. Demonstrate these steps:

Write the code for heap array:

// Create the minimum heap void makeminheap (int A [], int N) {for (INT I = n/2-1; I> = 0; I --) minheapfixdown (, i, n );}

So far, all heap operations have been completed (Note 1). Let's take a look at how to sort data structures like heap.

Heap sorting

First, we can see that 0th pieces of data in the heap are the smallest pieces of data in the heap after the heap is built. Retrieve the data and delete the heap. In this way, the 0th pieces of data in the heap are the smallest pieces of data in the heap. Repeat the above steps until only one piece of data in the heap is taken out directly.

Since the heap is simulated using arrays, after the array is heap, a [0] And a [n-1] are exchanged for the first time, and then a [0... N-2] restore the heap. For the second time, exchange a [0] with a [n-2], and then exchange a [0... N-3] restore the heap and repeat this operation until a [0] exchanges with a [1. Since every time the smallest data is merged into the next ordered interval, the entire array is sorted after the operation is complete. Similar**Select sort directly**.

void MinheapsortTodescendarray(int a[], int n){ for (int i = n - 1; i >= 1; i--) { Swap(a[i], a[0]); MinHeapFixdown(a, 0, i); }}

Note that the minimum heap sorting result is a descending array. To obtain an ascending array, you can use the maximum heap.

Since the time complexity of each heap recovery is O (logn), a total of n-1 heap recovery operations were performed, plus n/2 downward adjustments when the heap was created earlier, the time complexity of each adjustment is also O (logn ). The sum of the second operation time is O (n * logn ). Therefore, the time complexity of heap sorting is O (n * logn ). STL also implements heap-related functions. For details, refer to STL Series 4 heap.

Note 1 as a data structure, it is best to encapsulate its data and methods with classes, so that even operations are easy to understand. In addition to using heap sorting, heap can also be used in many cases to conveniently and efficiently process data. We will introduce it one by one later.

Reprinted please indicate the source, original address: http://blog.csdn.net/morewindows/article/details/6709644