Heap Data Structure + heap sorting + Implementation of the maximum priority queue, heap sorting queue

Source: Internet
Author: User

Heap Data Structure + heap sorting + Implementation of the maximum priority queue, heap sorting queue

For heap sorting, we must first know what the heap data structure is. The heap data structure is a complete binary tree, but it has its own nature.
For example, the maximum heap is A [PARENT [I]> = A [I]; that is, the value of each node is greater than or equal to the value of its left and right children, it is less than or equal to the value of its parent node. Here we will only discuss the situation of the maximum heap. We know that A full Binary Tree corresponds to the form of A maximum heap. What we need to do is to convert the binary tree into the largest heap. This is the so-called maximum heap maintenance. We define the function MaxheapFY (, i.
Code:

/*** MaxheapFY (A, I): maintains the maximum heap property of location I. In this case, assume that the two binary trees with left (I) and right (I) as the root are the largest heap, */void MaxheapFY (int * A, int I) {// maintain the maximum heap property of location I, int l, r, now; l = LEFT (I ); r = RIGHT (I); now = I; // record the current node if (l <= heapsize & A [l]> A [now]) {now = l; // exchange A [l] And A [I] and recursively maintain the next current node now} if (r <= heapsize & A [r]> A [now]) {now = r; // exchange A [l] And A [I], and recursively maintain the next current node now} if (now! = I) {// It is not the current node and needs to be exchanged. swap (A [I], A [now]) is exchanged with the maximum value of the current node and the left and right children. maxheapFY (A, now); // recursively maintain the current node until the leaf node }}

The following describes how to build a heap based on the maintenance nature of the largest heap:
/**
* BuildMaxHeap (A, n): enter an unordered array A [1... N], create the largest heap. We know the array A [(n/2 + 1 )... All elements in n] are
* Each leaf node in the tree can be regarded as the largest heap of an element. We still remember that the MaxheapFY (A, I) function is used for maintenance.
* The premise of the largest heap is that its child Left (I) and Right (I) are the largest heap. Therefore, we can use the MaxheapFY (A, I) function: [(n/2 ).. 1]
* Create the maximum heap.
*/
Code:

Void BuildMaxHeap (int * A, int n) {// A [1 .. n] heapsize = n; // global variable, indicating the maximum heap size for (int I = n/2; I> = 1; I --) {// from n/2 .. 1. Maintain the maximum heap nature of each node in the heap: the node value is greater than the child value MaxheapFY (A, I );}}

We know that the first element of the largest heap must be the maximum value in the array, and we can exchange (A [1] and A [n]). in this case, A [n] is already the largest value, and you do not need to operate it. You only need to maintain the maximum heap property of the 10-n-1 elements whose subscript is 1, after the operation, it becomes the maximum heap of N-1 elements. Continue the above swap operation until the remaining two elements are sorted.
Code:

Void HeapSort (int * A, int n) {BuildMaxHeap (A, n); // create the maximum heap for (int I = n; I> = 2; I --) {// cout <A [1] <""; swap (A [1], A [I]); // interact A [1] and A [I] so that heapsize is the largest element in A [I] --; // heap size minus 1, this facilitates the next operation to remove the sorted element MaxheapFY (A, 1); // At this time, A [1] may not necessarily meet the nature of the maximum heap, re-maintain the maximum heap nature of subscript 1 }}

So far, we have completed the establishment of the largest heap and the Code for heap sorting. The biggest heap is more important, that is, the implementation of the maximum priority queue based on the largest heap, the maximum priority queue is the maximum element priority. Of course, there is also a minimum priority queue, which is constructed based on the minimum heap. Once we have learned the data structure, we know that each data structure has its own properties and operations (methods or functions). Let's take a look at the operations that the maximum priority queue should support. Certainly there will be: operations such as taking the first element of the queue, deleting the first element, inserting the element, and modifying the value of the element keyword.
/**
* The Operations corresponding to the maximum priority queue are given below
* 1. PQueue_Insert (A, x): inserts element x into the set S. The set S corresponds to A queue with the highest priority.
* 2. PQueue_Maxnum (A): returns the element with the largest key value in the maximum priority queue S.
* 3. PQueue_Pop (A): Remove and delete the elements that return the maximum key value of queue S of the maximum priority.
* 4. PQueue_IncresaseKey (A, x, key): add the key value of element x to the key (corresponding to the largest priority queue here)
*
* Special Note :::
* The priority queue is maintained and operated after the largest heap is created. Therefore, the highest priority queue is in progress.
* Before the operation, you must first run the initial Hu function PQueue_Init (A, n): the initialization length is n set S, and the maximum heap is constructed.
*/
Various function code implementation:
Initialization function PQueue_Init (A, n ):

Void PQueue_Init (int * A, int n) {BuildMaxHeap (A, n); // call the function for initialization}

The function PQueue_Maxnum (A) that returns the largest element ):

int PQueue_Maxnum(int *A){    return A[1];}

Remove and return the first element PQueue_Pop (A) of the maximum priority queue ):

Int PQueue_Pop (int * A) {if (heapsize> = 1) {int max = A [1]; A [1] = A [heapsize]; -- heapsize; // heap size (maximum priority queue size) minus 1, MaxheapFY (A, 1); // maintain the return max of the maximum heaps remaining ;} else return-1; // deletion failed}

The PQueue_IncresaseKey (A, x, key) function that is maintained after the element keyword is modified ):

Int PQueue_IncresaseKey (int * A, int I, int key) {// increase the key value of A [I] if (key <A [I]) return-1; // It does not meet the maximum heap requirement (defined only here). A [I] = key; // note that all the ancestors of I may not satisfy the maximum heap nature at this time, // Therefore, Yuyao determines whether all the ancestors meet the maximum heap requirements. while (I> 1 & A [PARENT (I)] <A [I]) {swap (A [I], A [PARENT (I)]); I = PARENT (I ); // determine whether the current node reaches the maximum heap or reaches the parent node }}

Insert element PQueue_Insert (A, x ):

Void PQueu_Insert (int * A, int key) {// the size of the queue with the highest priority increases by 1 + heapsize; A [heapsize] = INF; // assign a value to the newly added node to the smallest value that never exists (only corresponding to the maximum priority queue of the Program) // The remaining operation is equivalent to adding the keyword of the subscript heapsize to the key and maintaining it. Just call the function directly. PQueue_IncresaseKey (A, heapsize, key );}

Now all functions are defined and implemented, which is the maximum priority queue.

All codes and tests in the appendix (a few ):

/*** @ Xiaoran * heap sorting is an algorithm that uses the data structure heap for in-situ sorting. * First, understand the heap data structure, how to construct the maximum heap and maintain the maximum heap * and construct an efficient priority queue using the data structure */# include <iostream> # include <cstdio> # include <map> # include <cstring> # include <string> # include <algorithm> # include <queue> # include <vector> # include <stack> # include <cstdlib> # include <cctype> # include <cmath> # define LL long # define PARENT (x) x> 1 # define LEFT (x) x <1 # define RIGHT (x) (x <1) + 1 # define INF-100000000 # define P T (A, n) for (int I = 1; I <= n; I ++) cout <A [I] <""; cout <endl; using namespace std; int heapsize = 0; // heap size/*** output A [1 .. n] */void Print (int * A, int n) {for (int I = 1; I <= n; I ++) cout <A [I] <"; cout <endl;}/*** MaxheapFY (A, I): maintains the maximum heap nature of location I, assume that the two binary trees with left (I) and right (I) as the root are the largest heap, */void MaxheapFY (int * A, int I) {// maintenance position I maximum heap properties, int l, r, now; l = LEFT (I); r = RIGHT (I); now = I; // record the current node if (l <= heapsize & A [l]> A [now]) {now = l; // exchange A [l] and [I], and recursively maintain the next current node now} if (r <= heapsize & A [r]> A [now]) {now = r; // exchange A [l] And A [I], and recursively maintain the next current node now} if (now! = I) {// It is not the current node and needs to be exchanged. swap (A [I], A [now]) is exchanged with the maximum value of the current node and the left and right children. maxheapFY (A, now); // recursively maintain the current node until the leaf node}/*** BuildMaxHeap (A, n): enter an unordered array A [1... n], create the largest heap. We know the array A [(n/2 + 1 )... the elements in n] are * leaf nodes in the tree. Each node can be regarded as the largest heap of an element. We still remember MaxheapFY (A, I) the premise that the function is used to maintain * The maximum heap is that its child Left (I) and Right (I) are the largest heap. Therefore, we can use the MaxheapFY (A, I) function, from I: [(n/2 ).. 1] * Create the maximum heap. */Void BuildMaxHeap (int * A, int n) {// A [1 .. n] heapsize = n; for (int I = n/2; I> = 1; I --) {// from n/2 .. 1. Maintain the maximum heap nature of each node in the heap: the node value is greater than the child value MaxheapFY (A, I );}} /*** the following two functions are used to construct the HeapSort (A, n) Heap sorting algorithm. * Call BuildMaxHeap (A, n) to input the array A [1 .. n] Create as the maximum heap. Note that the maximum value of the array is A [1]. * we only need to swap A [1] and A [n] and remove A [n] (-- heapsize ), maintain the maximum heap nature of Line 1: MaxheapFY (A, 1), * until the heap size n-1 drops to 2 */void HeapSort (int * A, int n) {BuildMaxHeap (A, n); // create the maximum heap for (int I = n; I> = 2; I --) {// cout <A [1] <""; swap (A [1], A [I]); // interact A [1] and A [I] so that heapsize is the largest element in A [I] --; // heap size minus 1, this facilitates the next operation to remove the sorted element MaxheapFY (A, 1); // At this time, A [1] may not necessarily meet the nature of the maximum heap, re-maintain the maximum heap nature of subscript 1}/*** next we will discuss the implementation of the maximum priority queue based on the maximum heap * obviously the priority queue is a data structure, we know that any data structure has its corresponding operations (functions) * The following lists the operations corresponding to the maximum priority queue * 1. PQueue_Insert (A, x ): insert element x into set S. Set S corresponds to A maximum priority queue * 2. PQueue_Maxnum (A): returns the maximum priority queue S, elements with the maximum key value * 3 and PQueue_Pop (A): Remove and return the elements with the maximum key value of queue S with the maximum priority, and delete * 4 and PQueue_IncresaseKey (A, x, key ): add the keyword value of element x to the key (corresponding to the maximum priority queue here) ** Note: * after the priority queue is created based on the maximum heap, therefore, before performing the maximum priority queue * operation, you must first run the initial Hu function PQueue_Init (A, n): the initialization length is n set S, construct the largest heap **/void PQueue_Init (int * A, int n) {BuildMaxHeap (A, n ); // call the function to create the maximum heap for initialization} int PQueue_Maxnum (int * A) {return A [1];} int PQueue_Pop (int *) {if (heapsize> = 1) {int max = A [1]; A [1] = A [heapsize]; -- heapsize; // heap size (maximum priority queue size) minus 1, MaxheapFY (A, 1); // maintain the return max of the maximum heaps remaining ;} else return-1; // deletion failed} int PQueue_IncresaseKey (int * A, int I, int key) {// increase the key value of A [I] if (key <A [I]) return-1; // it does not meet the maximum heap requirement (only defined here) A [I] = key; // note that all the ancestors of I may not meet the nature of the maximum heap at this time, // Therefore, Yuyao determines whether all the ancestors meet the maximum heap requirements. while (I> 1 & A [PARENT (I)] <A [I]) {swap (A [I], A [PARENT (I)]); I = PARENT (I ); // determine whether the current node reaches the maximum heap or reaches the parent node} void PQueu_Insert (int * A, int key) {// the size of the queue with the highest priority is increased by 1 + heapsize; A [heapsize] = INF; // assign a value to the newly added node to the smallest value that never exists (only corresponding to the maximum priority queue of the Program) // The remaining operation is equivalent to adding the keyword of the subscript heapsize to the key and maintaining it. Just call the function directly. PQueue_IncresaseKey (A, heapsize, key);} int main () {int A [9] = {, 7};/*** heap sorting test */Print (A, 8); HeapSort (, 8); Print (A, 8);/*** maximum priority queue test */PQueue_Init (A, 8); cout <PQueue_Maxnum (A) <endl; cout <PQueue_Pop (A) <endl; cout <PQueue_Maxnum (A) <endl; PQueue_IncresaseKey (A, 5, 10); PQueu_Insert (A, 12 ); cout <PQueue_Maxnum (A) <endl; cout <PQueue_Pop (A) <endl; cout <PQueue_Maxnum (A) <endl; return 0 ;}

Related Article

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.