Heap definition and algorithm analysis

Source: Internet
Author: User

Heap is an ADT similar to the binary search tree. However, unlike the binary search tree, it is mainly reflected in two aspects. First, the binary search tree can be looked at in order, while the heap is in order. This concept is weak. However, in order to make the priority queue operation effective, this fully meets the requirements. Second, the binary search tree has multiple shapes, and the heap is always a Complete Binary Tree.
The heap is a complete binary tree, which can be empty or:
(1) The search keywords contained in the root are greater than or equal to the search keywords of each child.
(2) The root contains the heap as the subtree.
In the definition of this heap, the root item contains the largest search keyword. Such a heap is called maxheap. Relatively speaking, minheap places the item containing the minimum search keyword in the root.
The heap is a Complete Binary Tree. Therefore, if you know the maximum size of the heap, you can use the array-based implementation of the binary tree. Figure 1 shows the heap and Its Array representation. The search keyword of the child in the heap node is greater than or equal to that of the node. In addition, in the heap, the child's search keywords are irrelevant: in other words, the child does not know that the search keywords contained by the child are larger.


Figure 1 heap and array Representation

 

Array-based implementation of heap
* Items: heap item Array
* Size: the integer that represents the number of items in the heap.
The array items corresponds to the tree-based array representation. In the following discussion, we assume that the heap is an integer for simplicity.
Heapdelete
Consider the heapdelete operation first. Where is the largest search keyword in the heap? Because the search keywords of each node are greater than or equal to the search keywords of any child, the maximum search keyword must be in the root of the tree. In this way, step 1 of the heapdelete operation is:
// Return the item in the root
Rootitem = item [0];
This is simple, but you must also delete the root. After deleting the root, two separate heaps are left, as shown in Figure 2-. Therefore, you need to convert the remaining points into a heap. When you start the conversion, extract the entries of the last node in the tree and put them in the root, as shown below:
// Copy the item from the last node into the root
Item [0] = item [size-1];
// Remove the last Node
-- Size
2-B shows that the result given to the step is not necessarily a heap. However, this is a complete Binary Tree, and both left and right Subtrees are heap. The only problem is that the root item may not be in the correct position. Such a structure is called semiheap ). A method is required to convert a half heap into a heap. One strategy is to gradually move the root item down until the node in the correct position is stopped. To this end, we first compare the half-heap root search keywords with the child search keywords. If the root search keyword is smaller than the greater one in the Child Search Keyword, the item of the root and the greater child will be exchanged. The so-called greater child, that is, the search keyword is greater than the Search Keyword of the other child.


Figure 2 (a) Split heap (B) Half heap
Figure 3 shows the heapdelete operation. After only one exchange, the value 5 is moved down to the correct position: However, generally, multiple exchanges are required. In fact, once the root item and the greater child C item are exchanged, C becomes the root of the half heap (note that C does not move, but it changes its value ). This policy leads to the following regression algorithm.


Figure 3 Delete from heap

heapRebuild(inout items :arrayType,in root :integer,in size :integer)//Coverts a semiheap rooted at index root into a heap //Recursively trickle the item at index root down to //its proper position by swapping it with its larger child ,if the //child is larger than the item//if the item is at a leaf ,nothing needs to be doneif(the root is not leaf){//root must hace a left childchild=2*root+1;if(the root has a right child){rightChild=child+1;if(items[rightChild].getKey()>items[child].getKey())child=rightChild;}//if the item in the root has a smaller search key//than the search key of the item in the larger//child,swap itemsif(items[root].getkey()<items[child].getkey()){swap items[root] and items[child]//transform semiheap rooted at child into a heapheapRebuild(items,child,size);}}//else root is a leaf ,so you are done

Figure 4 shows the recursive call of heaprebuild.


Figure 4 recursive call of heaprebuild.
Heapdelete uses heaprebuilt. As follows:
// Return the item from the last node into the root
Rootitem = item [0];
// Copy the item from the last node into the root
Items [0] = items [size-1];
// Remove the last Node
-- Size;
// Transform the semiheap back into a heap
Heaprebuild (items, 0, size );
This section briefly analyzes the efficiency of heapdelete. Tree is stored in an array. To delete nodes, You need to swap array elements instead of simply modifying several pointers. These exchanges are worth noting, but they do not mean inefficiency. How many times can an array element be exchanged at most? After heapdelete copies the entries of the last node in the tree to the root node, heaprebuilt moves this item down in the tree until the appropriate position. In the worst case, the item starts from the root node, move down along a single path to reach the leaves. Therefore, the number of array items that heaprebuilt must exchange is not greater than the height of the tree. The height of the Complete Binary Tree Containing N nodes is [log2 (n + 1)] (the smallest integer greater than log2 (n + 1 ). Data needs to be moved three times for each exchange. Therefore, the number of data moves required by heapdelete is 3*[log2 (n + 1)] + 1. Therefore, heapdelete is O (Log
N). In fact, this is very effective.
Heapinsert
The heapinsert algorithm has the opposite policy as heapdelete. Insert a new item at the bottom of the tree and move it up to the appropriate position, as shown in Figure 5. The move-up node is easy because the items [I] (instead of the root) node is always stored in items [(I-1)/2. The pseudo code of the heapinsert operation is as follows:


Figure 5 insert in heap

//insert newitem into the bootom of the treeitems[size]=newitem;//trickle new item up to appropriate spot in the treeplace =size;parent=(place-1)/2;while(parent>=0 and (items[place]>items[parent])){Swap items[place] and items[parent]place=parent;parent=(place-1)/2;}Increment size

The efficiency of heapinsert is the same as that of heapdelete. In other words, in the worst case, heapinset must exchange array elements from the leaf to the root path. Therefore, the number of exchanges cannot exceed the height. The height of the Complete Binary Tree is [log2 (n + 1)], so heapinsert is also O (log n ).

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.