Introduction to algorithms + heap sorting + heap forming a priority queue; Introduction to heap sorting

Source: Internet
Author: User

Introduction to algorithms + heap sorting + heap forming a priority queue; Introduction to heap sorting

Note: There are two types of heap: The maximum heap and the minimum heap. The stack we discuss below refers to the maximum heap. The minimum heap is similar in nature.

The heap data structure is an array object and can be considered as a full binary tree (except for the last layer, each layer of this binary tree is filled ); we use an array to store A heap, indicating that the heap array has two attributes: length [A] indicates the number of elements in the array, headsize [A] indicates the number of elements in the heap (that is, the elements in the array are not necessarily all elements in the heap ).
The following does not prove the nature of the heap:
For any node, its parent node is I/2 (I> 1); its left son is 2 * I, and its right son is 2 * I + 1;
For each node in the max heap, the following conditions are met: A [parent [I]> = A [I]
The height of n element Stacks is lgn.
The number of leaf nodes containing n element heaps is: n/2 + 1, n/2 + 2 ,......, N.

I. Heap adjustment functions-Preserve the heap nature
In this case, for node I, the left and right sub-trees of node I are a valid big-root heap, but node I does not meet the nature of the heap, then we can adjust to make the tree where I is the root node meet the nature of the heap. So what is the specific adjustment process? We make largest the largest one in A [I], A [I * 2], and A [2 * I + 1, if largest is not I, we will switch A [I] And A [largest] and recursively enter the subtree with largest as the root node to continue the adjustment. The Code is as follows:

Void MaxHeadfly (int * a, int I, int HeadSize) {// heap adjustment function: Adjust the subtree with I as the root, make it conform to the features of a large root heap (when both the left and right sub-trees are valid) // The maximum heap adjustment function is the most important function in heap sorting, is an important part of the following functions; // Its main idea is: first adjust the root node and then recursively adjust the affected left (right) subtree, until the leaf node int l = 2 * I, r = 2 * I + 1; // retrieve the number of the left and right son nodes of node I int largest; /// Number of the node that records the maximum value if (a [I] <a [l] & l <= HeadSize) largest = l; else largest = I; if (a [largest] <a [r] & r <= HeadSize) largest = r; if (largest! = I) {// recursively adjust the affected subtree swp (a [I], a [largest]); MaxHeadfly (a, largest, HeadSize );}}

2. Create a heap
Creating a heap is actually a process of constantly calling and adjusting functions. We know that the leaf node of the heap can be regarded as a big root heap that only contains one element. In this way, if we call the adjustment function from the first non-leaf node, this ensures that the left and right subtree of the node to be adjusted are both valid and that the tree to be adjusted is also valid. The Code is as follows:

Void BuildMaxHead (int * a, int n) {// maximum heap creation function: adjust the order of array elements, makes the array a big root heap // The nature of a full Binary Tree: the heap containing n elements, whose leaf node number is n/2 + 1, n/2 + 2... N; // For a leaf node, it can be regarded as a large root heap of a single element, which is known by the nature of the MaxHeadfly function. // If node I does not meet the nature of the large root heap, however, the left and right subtree are both valid big-root heaps, so after calling MaxHeadfly // adjustment, using I as the root node can constitute a legal big-root heap, the numbers of the left and right sons of a node are greater than those of the node. Therefore, we can call the heap adjustment function from the node number n/2--1 in sequence, then we can get a large heap. For (int I = n/2; I> = 1; I --) MaxHeadfly (a, I, n );}

Iii. Heap sorting
As the name implies, heap sorting uses the heap nature to sort arrays. For a heap, the feature we can use is that the elements in its root node are the largest, each time we exchange A [1] and A [HeadSize], the value of HeadSize is reduced by 1 after the exchange, and MaxHeadfly (a, 1, HeadSize) is called) adjust the heap so that A [1] becomes the largest of the remaining elements, and continue the process. Finally, an ordered array is obtained. The time complexity of heap sorting is nlgn. The specific code implementation is as follows:

Void HeadSort (int * a, int n) {// heap sorting function: sorts n elements in the array from small to large, time Complexity nlgn // we know that if an array forms a large heap, then the root node a [1] must be the largest element. // if we swap a [1] with a [n, then a [n] is the largest element. // However, the heap composed of a [1 -- n-1] may no longer meet the nature of the largest heap. We call MaxHeadfly (, 1, n-1) adjusted to the maximum heap // then a [1] becomes the largest element in a [1 -- n-1, then we exchange a [1] and a [n-1], then a [n-1] And a [n] are ordered. /// Continue this process until the size of the heap is reduced to 2, and then the last adjustment and exchange are performed. array a is arranged in ascending order. /// Time complexity: The time O (n) of a large root heap is established, and the O (lgn) Time is adjusted for a total of n-1 times each time. Therefore, the total complexity is nlgn BuildMaxHead (a, n ); /// create a large root heap int HeadSize = n; for (int I = n; I> = 2; I --) /// the size of the heap is continuously reduced {swp (a [1], a [I]); HeadSize --; // the size of the heap will be reduced after switching MaxHeadfly (, 1, HeadSize); // The root node is changed, and the size is changed to a large root heap }}

The following is a complete heap Sorting code:

# Include <iostream> # include <cstdio> # include <cstring> using namespace std; int swp (int & a, int & B) {int t = a; a = B; B = t;} void MaxHeadfly (int * a, int I, int HeadSize) {int l = 2 * I, r = 2 * I + 1; /// retrieve the number of the left and right son nodes of node I, int largest; /// Number of the node that records the maximum value if (a [I] <a [l] & l <= HeadSize) largest = l; else largest = I; if (a [largest] <a [r] & r <= HeadSize) largest = r; if (largest! = I) {// recursively adjust the affected subtree swp (a [I], a [largest]); MaxHeadfly (a, largest, HeadSize );}} void BuildMaxHead (int * a, int n) {for (int I = n/2; I> = 1; I --) MaxHeadfly (a, I, n );} void HeadSort (int * a, int n) {BuildMaxHead (a, n); // create a large root heap int HeadSize = n; for (int I = n; i> = 2; I --) // the size of the heap is continuously reduced {swp (a [1], a [I]); HeadSize --; /// reduce the heap size after switching MaxHeadfly (a, 1, HeadSize); // The root node is changed and changed to a large root heap.} int main () {int n = 5, a [10]; cout <"enter" <n <"count:" <endl; for (int I = 1; I <= n; I ++) cin> a [I]; HeadSort (a, n); cout <"sorted array:" <endl; for (int I = 1; I <= n; I ++) cout <a [I] <"; cout <endl; return 0 ;}

4. priority queue
For a general queue, it is suitable for the first-in-first-out type (for the first-out type), but for the first-out type, each queue is the largest/smallest element. The heap can be used to perform basic operations on the priority queue. For specific function operations and their principles of the priority queue, see the following code.

# Include <iostream> # include <cstring> # include <cstdio> using namespace std; # define INF 0x3f3f3f3f // a general queue meets the first-in-first-out nature, but the preferred queue is different, /// always the largest/smallest first team. With the help of the heap nature, we can // optimize any operation of the queue in lgn time void swp (int & a, int & B) {int t =; a = B; B = t;} void MaxHeadfly (int * a, int I, int HeadSize) // heap adjustment function {int largest; int l = I * 2, r = 2 * I + 1; if (a [I] <a [l] & l <= HeadSize) largest = l; else largest = I; if (a [largest] <a [r]) largest = r; if (largest! = I) {swp (a [I], a [largest]); MaxHeadfly (a, largest, HeadSize) ;}} void BuildMaxHead (int * a, int n) /// create a maximum heap {int k = n/2; for (int I = k; I> = 1; I --) MaxHeadfly (a, I, n );} /// The following is the int MaxNum (int * a) Operation of the priority queue. // retrieve the largest element {return a [1]; /// directly return} void IncreaseKey (int * a, int x, int k) {// increase the value of the element numbered x in the heap to k, k cannot be smaller than the original value. /// This improvement may only result in the parent node not meeting the nature of the maximum heap, so check a [x] = k directly and recursively; while (x> 1 & a [x/2] <a [x]) {swp (a [x], a [x/2]); x = x/2;} int ExtractMax (int * a, int & HeadSize) {// remove the largest element in the heap, return its value // The thought is similar to an adjustment of heap sorting: first, we exchange the values of a [1] and a [HeadSize] // and then subtract 1 from the value of HeadSize (equivalent to removing a leaf node ); then, you can call // MaxHeadfly (a, 1, HeadSize) to adjust the heap to ensure its nature. Swp (a [1], a [HeadSize]); HeadSize --; MaxHeadfly (a, 1, HeadSize); return a [HeadSize];} void Insert (int *, int & HeadSize, int x) {// Add an element x to the heap // thought: Add a leaf node to the heap first, assign the value to-INF // and then call the above adjustment function to adjust the value of the leaf node to x HeadSize ++; /// Add a leaf node a [HeadSize] =-1 * INF; IncreaseKey (a, HeadSize, x);} int main () {int a [10]; int n = 5; cout <"enter 5:" <endl; for (int I = 1; I <= n; I ++) cin> a [I]; int HeadSize = n; BuildMaxHead (a, n); // retrieves the largest cout element in the queue <"the largest element is: "<MaxNum (a) <endl; ExtractMax (a, HeadSize); cout <" after removing the largest element, the largest of the remaining elements is: "<MaxNum (a) <endl; // Add 4th elements to 100 IncreaseKey (a, 4,100 ); after cout <"adds 4th elements to 100, the maximum element is:" <MaxNum (a) <endl; /// Insert 110 into the queue Insert (a, HeadSize, 110); cout <"after inserting 110, the maximum element is:" <MaxNum () <endl; return 0 ;}

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.