Seven heap and heap sorting in the Classical Vernacular algorithm series

Source: Internet
Author: User
  Heap sortingAnd High-speed sorting, Merge SortingThe 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 fully binary tree or approximately a fully 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 child node.

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 a parent node is always greater than or equal to the key value of any child nodeMax heap. When the key value of the parent node is always less than or equal to the key value of any child nodeMinimum heap. Display a minimum heap:

Because there are few other kinds of 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 Description", and then shows the implementation code. It is best to first clarify the diagram and then look at the code.

Heap insertion

Each insert operation puts the new data at the end of the array. It can be found that the parent node from the new data to the root node must be an ordered series. Today's task is to insert this new data into this ordered data-this is similarInsert sort directlyTo merge a data into an ordered interval, it is not difficult to write the heap adjustment code when inserting a new data by comparing the three implementations of directly inserting sorting in the vernacular classical algorithm series II:

// New? The parent node of node I 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 in the minimum heap? New data nnumvoid minheapaddnumber (int A [], int N, int nnum) {A [n] = nnum; minheapfixup (A, n );}
Delete heap

By definition, only 0th pieces of data can be deleted each time in the heap. To facilitate heap reconstruction, the actual operation is to assign the value of the last data to the root node, and then start from the root node to make a top-down adjustment. When adjusting, first find the smallest node in the left and right son nodes. If the parent node is smaller than the smallest child node, it means no adjustment is required. If the parent node is switched with it, then the subsequent nodes are considered. It is equivalent to a "sink" process of data from the root point. The following code is provided:

// Start from the start of the I node. N indicates that the total number of nodes starts 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, for example:

Obviously, for the leaf node, it can be thought that it is already a valid heap, that is, 20, 60, 65, 4, and 49. Each of them is a valid 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 );}


Now, all the heap operations have been completed (Note 1). Let's take a look at how to use the heap data structure for sorting.

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. Extract the data and then 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.

Because the heap is simulated by arrays, after the array is heap, a [0] And a [n-1] are exchanged for the first time, and then a [0... N-2] restores the heap again. For the second time, exchange a [0] with a [n-2], and then exchange a [0... N-3] restores the heap again and repeats this operation until a [0] exchanges with a [1. Because every time the smallest data is merged into the next ordered interval, the entire array is sorted after the operation is complete. SimilarSelect 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 smallest heap sorting result is a descending array. To obtain an ascending array, you can use the largest heap.

Because the time complexity of restoring the heap again is O (logn), a total of n-1 heap operations are resumed again and again, 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, allowing you to read the four heap in the STL series.

 

 

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 sorting can be used in many cases to process data conveniently and efficiently.

 

 

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

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.