Sorting Algorithm 3-heap sorting and priority queue

Source: Internet
Author: User

First of all, do not be misled by names. priority queue is not a sort-hungry algorithm, but a data structure. This structure is different from the general first-in-first-out queue. Each time it leaves the queue, It is the element with the highest priority. When an element with a specified priority enters the queue, it can be quickly ranked in the queue. Put the two together because the priority queue is designed using the heap sorting method.

First, let's first look at the heap sorting. Heap is a Complete Binary Tree. We have mentioned the Complete Binary Tree before, that is, it is filled before, except for the last layer. The last layer has always had leaves on the left, but from a node, there are no leaves behind the node. (It is really a waste of time to say this data structure with your mouth. If I don't make it clear, you can do it on your own !) The obvious advantage of this structure is that it can be conveniently implemented using arrays (instead of pointers). If the entire binary tree is numbered from left to right, from top size, from 0, the subscript I of the array corresponds to a node, then the left and right children of this node are: 2 * I + 1, 2 * I + 2; its parent node is (I-2) /2.

After talking about the Complete Binary Tree, let's look at the maximum heap and the minimum heap. The maximum heap is a structure in which the keys of a child node are smaller than or equal to the parent node. If the keys of a child node are greater than or equal to the parent node, it is called the minimum heap.

With this write concept, we can talk about heap sorting.

The heap sorting process is roughly divided into four major steps: 1. Use the original array to create a maximum heap. In this case, the largest element in the array must be saved in data [0. 2. Exchange the data [0] of the largest heap with the data [n-1] element, and then the largest element is in data [n-1. 3. Ignore the last element and adjust the entire heap. It is the largest heap after element exchange. 4. Exchange the data [0] of the Max heap with the data [N-2], and so on.

The difficulty of the entire program is: how to adjust a heap to make it the largest heap. This problem can be solved recursively: If the left and right subtree of a node is already the largest heap, compare the root node with the left and right subtree (if necessary) the largest exchange with left and right Subtrees. However, after the exchange, one of the left and right Subtrees may not be the largest push) the subtree with the root tree repeats the previous process until it meets the leaf node. The procedure for this part is as follows:

// Adjust the heap to make the subtree with index as the root become the largest heap void heapadjust (parraylist list, int index, int length) {// left child int lchild = Index * 2 + 1; // right child int rchild = Index * 2 + 2; // maximum subscript int largest; // find the subscript of the maximum value and store it in largest if (lchild <= Length & list-> data [lchild]> list-> data [Index]) largest = lchild; elselargest = index; If (rchild <= Length & list-> data [rchild]> list-> data [Largest]) largest = rchild; // if you need to switch if (largest! = Index) {// exchange them int TMP = List-> data [Index]; List-> data [Index] = List-> data [Largest]; list-> data [Largest] = TMP; // After switching, You need to determine whether the three nodes at the next level need to adjust heapadjust (list, largest, length );}}

 

With this function, other problems can be solved. For example, to use an array to initialize a maximum heap, you need to start from the parent node of the last leaf node, call the above heapadjust function in sequence:

// Call heapadjust from the bottom to convert the array into a maximum heap void buildmaxheap (parraylist list) {// starting from the last Father's Day, until the root of the tree for (INT I = (list-> length-2)/2; I> = 0; -- I) heapadjust (list, I, list-> length );}

 

The rest is as described above: swap the largest heap with the last element of the array, ignore the last element, and re-adjust the heap. Repeat the preceding steps with the last and second elements:

// Heap sorting void heapsort (parraylist list) {buildmaxheap (list); printf ("Maximum heap:"); printarraylist (list ); int Len = List-> length-1; for (INT I = List-> length-1; I> 0; -- I) {int TMP = List-> data [0]; List-> data [0] = List-> data [I]; List-> data [I] = TMP; printf ("after switching"); printarraylist (list); // after sorting, ignore the last element, and then consider the first n-1 elements -- Len; heapadjust (list, 0, len);} printf ("Final Result:"); printarraylist (list );}

 

In this way, the heap sorting is completed.

I personally think that although this algorithm is well-designed, it does not compress much compared with the fast sorting and Merge Sorting mentioned above. One of its important applications is to implement priority queues.

Let's take a simple look: For a priority queue, we need to support the following key operations: (what else does it mean to determine whether the queue is empty? The length of the returned queue is omitted)

(1) Push: Insert elements into the priority queue.

(2) Top: elements with the highest priority returned

(3) Pop: Delete the element with the highest priority

(4) increase: increases the priority of an element to a certain number.

With the heap sorting above, we will not be confused about these operations. When we already have the largest heap:

(2) operation: returns the first element a [0] with the largest push.

(3) operation: similar to heap sorting, replace a [0] with a [n-1], and then reduce the length of the array by 1 (ignore the last element ), then adjust the heap.

(4) operation: Set a [I] to a specified priority. Then, when I> 1 and I have a parent node smaller than I, I always do two things: a. Exchanges the value of a [I] with its parent node. B. Increment I to the serial number of the parent node.

(1) operation: With (4) operation, in fact (1) it is easy to implement. Insert a node with a very low priority to the heap, then, you can use the increase function to increase the priority of a specified value.

The following describes the specific functions:

// Return the first element int top (parraylist list) {return list-> data [0];} // The output int POP (parraylist list) {int head = List-> data [0]; List-> data [0] = List-> data [list-> length-1]; -- list-> length; // adjust the heap to the maximum heapadjust (list, 0, list-> length); return head;} // raise the priority of a specified position to a number of void increasekey (parraylist list, int index, int key) {If (list-> data [Index]> key) {printf ("New Key must bigger than old key! \ N "); return;} elselist-> data [Index] = key; int TMP; // when the child node is not a root node and the parent node is smaller than the child node, while (index> 0 & list-> data [(index-2) /2] <list-> data [Index]) {// exchange the element TMP = List-> data [Index] between the parent node and the child node. list-> data [Index] = List-> data [(index-2)/2]; List-> data [(index-2)/2] = TMP; // continue to go to Index = (index-2)/2;} // enter the queue void push (parraylist list, int key) {If (list-> length = List-> size) {list-> DATA = (int *) realloc (list-> data, sizeof (INT) * List-> size * 2); List-> size = List-> size * 2 ;} // set the initial priority to minimum list-> data [list-> length] =-1; increasekey (list, list-> length, key ); ++ list-> length ;}

 

To be more "like" the style in the STL library, the traditional enqueue and dequeue are not used here to indicate that the team is in the queue.

 

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.