Heap, heap sorting, priority queue (C ++ implementation)

Source: Internet
Author: User

 

So far, I have known two types of heap: one is memory, and the common purpose is to allocate dynamic memory (in C/C ++ ), the other is the data structure discussed here.

I. Heap

The heap in the data structure is also called a binary heap. As the name suggests, we can regard it as a Complete Binary Tree. Each element has a maximum of two children, which are regarded as the left and right children respectively. Based on the relationship between the element and its child, the heap can be divided into the maximum heap and the minimum heap. The maximum heap is the parent's value not less than the left or right (if any) value. Correspondingly, the minimum heap is that the parent's value is not greater than the child's value.

Similar to binary tree notation, heap can be stored in sequence or chain. Here I use sequential storage. Chained storage involves pointer operations, which is a little more troublesome. Since array storage is used, we need to understand the subscript relationship between the parent node and the child node of the ordered binary tree.

Parent (I) = I/2; left (I) = 2I + 1; right (I) = 2I + 2

Note that I starts from 0. When I starts counting from 1, the relationship is slightly different.

Two common applications of heap are heap sorting and priority queue, which are used in some algorithms (such as the Minimum Spanning Tree Algorithm. When performing operations on the heap, such as inserting or deleting elements, we must adjust the heap to ensure that the modified heap is not damaged, that is, the data structure is a heap. How can we maintain the nature of the heap?

Taking the largest heap as an example, assuming that the heap is stored in an array, the subscript of the element to be adjusted is I, and its left and right subtree are the largest heap. Perform the following operations:

1. find the maximum value in array [I], array [left (I)], array [Right (I)] (if both exist), and mark it as largest, if array [I] is the maximum value, the subtree rooted in it is already the largest heap, and the program ends. Otherwise, if a subnode of array [I] is the maximum value, replace array [I] with the child and go to step 2.

2. The value of the subnode whose subscript is largest after the switch is array [I]. The subtree whose root value is largest may violate the nature of the heap. Therefore, step 1 is executed for this subtree.

In the following function, I use heap_type to indicate whether the heap is the largest heap or the smallest heap, and perform different operations accordingly.

Template <typename T> void heapify (T * array, const int length, int I, heap_type) {if (I <length) {int extre_ele_index; extre_ele_index = I; if (I * 2 + 1 <length) // left child {If (type = max_heap) {If (array [extre_ele_index] <array [I * 2 + 1]) extre_ele_index = I * 2 + 1;} else {If (array [extre_ele_index]> array [I * 2 + 1]) extre_ele_index = I * 2 + 1 ;}} if (I * 2 + 2 <length) // right child {If (type = max_heap) {If (array [ex Tre_ele_index] <array [I * 2 + 2]) extre_ele_index = I * 2 + 2;} else {If (array [extre_ele_index]> array [I * 2 + 2]) extre_ele_index = I * 2 + 2;} If (extre_ele_index! = I) {T extre_ele; extre_ele = array [I]; array [I] = array [extre_ele_index]; array [extre_ele_index] = extre_ele; heapify (array, length, extre_ele_index, type );}}}

With the subprogram above, we can build the heap.

Think of the heap array as a complete binary tree. We need to adjust the elements in array in sequence starting from the first non-leaf node of the Complete Binary Tree until the first element of array, that is, the root of the Complete Binary Tree. The reason for the adjustment from the first non-leaf node is that the leaf node does not have any children, so obviously it satisfies the nature of the heap and thus there is no need for adjustment.

Template <typename T> void build_heap (T * array, const int length, heap_type type) {int I; for (I = length/2; I> = 0; -- I) {heapify (array, length, I, type) ;}// pay attention to the sequence number of the first non-leaf node} // pay attention to the I in the array (starting from 0) the numbers of the left and right children of each element.

In this way, we will build a heap.

Ii. Heap sorting

Heap sorting, as its name implies, is based on heap sorting. Because of the nature of the heap (the parent is not greater than or less than the child's value), the first element of the heap (or the root of the full Binary Tree) is always the largest (large, small) value in the heap. Heap sorting is the feature of heap. The process can be described as follows:

1. Exchange the first element with the last element of the heap.

2. Reduce the heap size by one.

3. The new value exchanged to the first position may violate the heap nature, so heapify is called to keep the heap.

4. Repeat 1, 2, and 3 until the heap has only one element.

Because step 1 puts the first element into the position where it should be placed after sorting, each time it is executed, an element in the array is sorted, and the size of the heap is naturally reduced by one.

// Sort_by indicates the ascending or descending order.

Template <typename T> void heap_sort (T * array, const int length, sort_by type) {int I; t extre_ele; If (type = ascend) build_heap (array, length, max_heap); elsebuild_heap (array, length, min_heap); // create a heap first to ensure that the first element is the extreme value. For (I = length-1; I> = 1; -- I) // I indicates the subscript of the last element of the subarray that has not been sorted. {Extre_ele = array [0]; array [0] = array [I]; array [I] = extre_ele; If (type = ascend) heapify (array, I, 0, max_heap); elseheapify (array, I, 0, min_heap );}}

Iii. priority queue

Priority Queues are divided into the maximum priority queue and the minimum priority queue, which are based on the maximum heap and the minimum heap respectively. As a type of queue, Priority Queues must first have basic operations such as queuing, queuing, taking the lead, and determining the air. What is different is the operations for changing the queue (queuing and queuing ), we need to make the above adjustments to ensure that the queue is still a heap.

In contrast to the heapify operation, heapify is adjusted from top to bottom, but from bottom to top. The new element is placed in a proper position.

1. because the queue is already a heap before joining the queue, you only need to compare it with your parents when you join the queue. If it is not heap, you can change it with your parents, then compare it with the parent in the new location until its relationship with the parent satisfies the heap nature.

Template <typename T> void priority_queue <t>: enqueue (T * Ele) {If (heap_size + 1> max_size) // The heap is full, {T * old_heap = heap; heap = new T [max_size * 2]; for (INT I = 0; I 

The operations performed by the team-out operation and heap sorting are almost identical. In each iteration of heap sorting, the first element is compared with the last element, the heap size is reduced by one, and heapify is called to maintain the heap nature. The team-out operation assigns the last element to the first element. The heap size is reduced by one and heapify is called to maintain the heap nature. Haha, no. The only difference is that one is a reconciliation, and the other is a value assignment.

template <typename T>void Priority_Queue<T>::dequeue( T *ele ){heap[0] = heap[heap_size-1];--heap_size;if( type == Minimum_Priority_Queue )heapify( heap, heap_size, 0, MIN_HEAP );elseheapify( heap, heap_size, 0, MAX_HEAP );}

The main operation of the priority queue is the above two, and the others are simpler.

The program file is in my resources. Address link: Click to open the link.

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.