Observe the change of the maximum heap after the element is inserted/deleted in the max heap.

Source: Internet
Author: User

Introduction:

The largest heap is actually very familiar. We also use a lot of things. The most classic is sorting. Its time complexity is o (nlogn), much higher than other sorting methods, for a classic application, for example, a gateway needs to check which of the most popular IP addresses/URLs are in the list of IP addresses/URLs accessed through it, because there are a large number of accesses, therefore, there may be a huge number of IP addresses/URLs. You must use algorithms to find the most popular IP addresses/URLs and then let the network administrator know. There are many similar examples, especially the TOP-N problem.


Analysis:

Summary:

Because the largest heap is a Complete Binary Tree first, that is, each row of it will only arrive at the following line when it is full, so we use arrays as internal storage to save space. Let's try to put the element in the heap above the array as much as possible. Note that what I am talking about here is as much as possible, rather than a sorted one, this is because as long as the root is the largest of all elements and any element is larger than the left and right child elements, there is no strict rule on who is bigger and who is smaller)


Heap insert operation:

Because an element is inserted into an already largest heap, it is certainly not expected to destroy its original Heap Structure as much as possible, so it is inserted to the end first. Then, assuming that this element is very large, it is obviously not in line with the heap definition at the end, so it must be compared with its parent element. If it is larger than its parent element, in this case, you can change the position with the parent element. This is the "Move Up" Operation) until it is moved up to the root. Of course, you must update the number of elements and variables in the heap.


Delete heap:

For the largest heap, the largest element is the first element in the heap, so you can delete it directly. However, this will leave a "hole" on the top of the original largest heap. We must move the last element in the heap to a proper position to reduce the heap size. So we need to adjust the remaining heap to restore it to a maximum heap. The method is to insert the last element of the heap into the hole just now, then compare the new value of the inserted element value hole), the left child element of the hole, and the size of the right child element of the hole. If the elements in the new insert hole are larger than the left and right sub-elements, it is generally impossible), so we have adjusted it, because the heap feature remains unchanged at other locations and we have not destroyed it. If the element value of the new hole is no larger than that of the Left or Right child element, you should switch the position between the new hole element and the child element, which is the "Sinking" operation ), until it sink to the bottom of the heap.


** Print the Heap Structure in tree form **

This is not introduced in many books. Most of the printing is layer-by-layer printing, but we think that the graph drawn on paper is structured. Therefore, using this flat data is obviously not conducive to our thinking, we must keep the heap tree structure. I carefully studied a heap and found that the position of each element in the heap depends on its current number of layers. The number of elements at any layer is also determined. So I found the following rule:


Assume that the maximum heap height is height, and the current total number of elements in the heap is currentSize:

Then, for the nth row, we can first print Math. pow (2, height-n) blank char,

Print the value of the first element in line n, and then print 2 * Math. pow (2. height-n) white space char. Print the element values and white space char in turn until the end of the row. The number of prints depends on the current number of rows. The rules are as follows:

For the last row, the number of prints is from currentSize-(Math. pow (2, I-1 ))

If not the last row, the print count is Math. pow (2, I-1)


Based on the above analysis, we quickly wrote out the implementation of this heap program, but it was not easy. At least I wrote it for more than an hour)

Package com. charles. algo. heap;/*** define a maximum heap ** @ author charles. wang **/public class MaxHeap {// the storage of the maximum heap is an array. For calculation, we do not place the content private int [] data in the first position; // heap size private int heapSize; // The number of current elements private int currentSize; public MaxHeap (int maxSize) {heapSize = maxSize; // create an array that can accommodate up to 1 is to enable the Header element of the array, because the operation starting from 1 is better to calculate data = new int [heapSize + 1]; currentSize = 0;}/*** check heap insertion here, because the elements in front of the array in the internal structure of the maximum heap are always built according to the maximum heap, the solution for inserting elements from the tail is: Step * 1: first, insert the current element to the end of the array. Step 2: recursively compare the current element and the Father's Day element. Step * 3: if the current element is greater than the father's day element, then move the current element up until it does not move. ** @ param value * @ return */public MaxHeap insert (int value) {// first checks whether the heap is full, if it is full, you cannot insert if (currentSize = heapSize) return this; // if the heap is not full, it indicates that there are still locations in the heap to insert, first, find the last position that can be inserted. // currentPos indicates the subscript int currentPos = currentSize + 1 of the array to be inserted. // insert it to the current position first, because it starts from 1, the array subscript operation must also be + 1 data [currentPos] = value; // then compare the current element with his father element // The current element is data [currentPos], and the father element is data [(currentPos/2], which is traversed to the root int temp; // If currentPos is 1, it indicates that the first element in the inserted heap does not need to be compared. // otherwise, if more than one element is inserted, use the element at the insert position to compare with its parent element while (currentPos> 1) {// if the current element is greater than the parent element, then switch their location if (data [currentPos]> data [currentPos/2]) {temp = data [currentPos/2]; data [currentPos/2] = data [currentPos]; data [currentPos] = temp; // update the current position currentPos = currentPos/2;} // otherwise, assuming that the existing heap is the maximum heap, it indicates that the inserted position is correct. You do not need to change else {break ;}// after the insertion is complete, add 1 currentSize ++ to the number of elements in the current heap; return this;}/*** check whether the heap is deleted because it is the largest heap. Therefore, deleting the maximum value is to delete the root element of the heap. In addition, you must also adjust the remaining heap to keep the largest heap. * because there is a gap in the maximum element location after the maximum element is deleted, the solution is: Step 1: copy the last element in the heap to this vacant position Step * 2: Compare the last element value in sequence, and the values of the left and right child elements in the current position, so as to lower the value to a proper position Step 3: remove the last element from the heap array */public int deleteMax () {// if the maximum heap is empty, the biggest element if (currentSize = 0) return 0 cannot be deleted; // otherwise, the heap is not empty, so the maximum element is always the first element in the heap, int maxValue = data [1]; // Since the maximum element is deleted, the currentSize In the heap is-1. Therefore, we must find a suitable new position for the last element in the array // int lastValue = data [currentSize] In the heap; // first move the last element in the heap to the first data [1] = lastValue of the Max heap; // clear the last element of the array stored in the heap. data [currentSize] = 0; // and the current heap size must be-1 currentSize --; // adjust the heap structure so that it is still the maximum heap int currentPos = 1; // set the current position as the root, and compare the Left and Right int leftPos = currentPos * 2 from the root; int leftValue; int rightValue; int temp; // If the left position is the same as the total capacity of the current heap, there are only two elements. One is the root element, one is the root's left element if (leftPos = currentSize) {// at this time, if the root left element data [2] is larger than the root element data [1, switch the two locations. if (data [2]> data [1]) {temp = data [2]; data [2] = data [1]; data [1] = temp ;}} else {// the condition that the Left position of the node is smaller than the number of elements in the current heap, then the node must have the right child element and the position is the left child element position + 1 while (leftPos <currentSize) {// obtain the value of the left child node of the current position leftValue = data [leftPos]; // obtain the value of the right subnode at the current position: rightValue = data [leftPos + 1]; // if the current value is greater than the left subnode and the right subnode, then it indicates that the current value position is correct, and a binary tree if (data [currentPos]> leftValue & data [currentPos]> rightValue) {break;} // otherwise, compare the Left and Right subnodes. // if the left subnode is greater than the right subnode and is greater than the current node), the left subnode and the current node are switched to else if (leftValue> rightValue) {temp = data [currentPos]; data [currentPos] = leftValue; data [leftPos] = temp; // At the same time, the current position is the position of the Left subnode, and the new left subnode is located at the left subnode currentPos = leftPos; leftPos = currentPos * 2;} // if the right subnode is greater than the left subnode (of course, if the value is greater than the current node), the Right subnode and the current node are switched to else {temp = data [currentPos]; data [currentPos] = rightValue; data [leftPos + 1] = temp; // At the same time, update the current position to the right subnode, and the new left subnode is located at the right subnode currentPos = leftPos + 1; leftPos = currentPos * 2 ;}}return maxValue;}/*** print the maximum heap according to the tree structure. The main idea is to print each row in sequence, the position of each element in each row, such as the number of null in the middle and the number of elements separated, are related to the current line number */public void printMaxHeapInTreeShape () {// calculate the height of the tree int height = (int) (Math. log (currentSize)/Math. log (2) + 1; // then calculate the number of elements in the last row of the tree if it is a full binary tree. int maxWidth = (int) Math. pow (2, height-1); // print each row for (int I = 1; I <= height; I ++) {// The algorithm used to print each row is: // The first line. Print the maxWidth blank char and then print the value of the first element. // the second line is displayed, print maxWidth/2 blank char, then print the value of 1st elements in the second row, and then print maxWidth blank char, print the second row of 2nd elements // the nth row, and print maxWidth * Math. pow (2,-(n-1) = Math. pow (2, height-n) blank char, // print the value of the first element in line N, and then print 2 * Math. pow (2. height-n) blank char, turn in turn until the end of this line // so, print Math first. pow (2. height-n) white space char printsingleblkcharwithgivennumber (int) (Math. pow (2, height-I); // print the gap between the element and the element in turn. // The exception here is the last line if (I = height) {for (int j = (int) (Math. pow (2, I-1); j <= currentSize; j ++) {// print the current element System. out. print (data [j]); // print the blank separation of element and element in this row printsingleblkcharwithgivennumber (2 * (int) (Math. pow (2, height-I) ;}// otherwise, the number of elements in this row is determined, so the number of loops is Math. pow (2, I-1), where I is the row number else {for (int j = (int) (Math. pow (2, I-1); j <(int) (Math. pow (2, I-1) + Math. pow (2, I-1); j ++) {// print the current element System. out. print (data [j]); // print the blank separation of element and element in this row printsingleblkcharwithgivennumber (2 * (int) (Math. pow (2, height-I);} System. out. println () ;}}/*** private method, print a specified number of white-space characters ** @ param number */private void printsingleblkcharwithgivennumber (int number) on a row) {for (int j = 0; j <number; j ++) System. out. print ("");}}


Lab:


Let's first look at the example of adding arbitrary elements to a heap in disorder. For example, we first apply for a heap with a maximum capacity of 15 elements:

// Insert multiple values to the heap in sequence to observe the heap changes. MaxHeap mx = new MaxHeap (15); System. out. println ("Empty heap created:"); System. out. println (); System. out. println ("insert 4:"); mx. insert (4); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 6:"); mx. insert (6); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 5:"); mx. insert (5); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 12:"); mx. insert (12); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 3:"); mx. insert (3); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 13:"); mx. insert (13); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("after inserting 9:"); mx. insert (9); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("inserted after 15:"); mx. insert (15); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 14:"); mx. insert (14); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 8:"); mx. insert (8); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("Insert 10:"); mx. insert (10); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 2:"); mx. insert (2); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 1:"); mx. insert (1); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 7:"); mx. insert (7); mx. printMaxHeapInTreeShape (); System. out. println (); System. out. println ("insert 11:"); mx. insert (11); mx. printMaxHeapInTreeShape (); System. out. println ();


The execution result is as follows:

Empty heap created: insert 4: 4 insert 6: 6 4 insert 5: 6 4 5 insert 12: 12 6 5 4 insert 3: 12 6 5 4 3 insert after 13: 13 6 12 4 3 5 Insert after 9: 13 6 12 4 3 5 9 insert after 15: 15 13 12 6 3 5 9 4 insert 14 after: 15 14 12 13 3 5 9 4 6 insert 8 after: 15 14 12 13 8 5 9 4 6 3 insert after 10: 15 14 12 13 10 5 9 4 6 3 8 after insertion 2: 15 14 12 13 10 5 9 4 6 3 8 2 after insertion 1: 15 14 12 13 10 5 9 4 6 3 8 2 1 insert 7 after: 15 14 12 13 10 5 9 4 6 3 8 2 1 7 insert 11 after: 15 14 12 13 10 5 11 4 6 3 8 2 1 7 9



The following example shows how to delete the largest element from the largest heap. We can also check whether the order of deletion is always the maximum value from the heap, and the order of deletion is sorted, the remaining heap remains in the largest heap shape after each deletion:

// Now we will demonstrate how to delete the heap. // because our Heap has 15 elements, we will delete the heap 15 times, then, check whether the deleted values are the maximum values in the heap and the remaining conditions in the heap for (int I = 1; I <= 15; I ++) {System. out. println ("no." + I + ":"); System. out. println ("the deleted Value is:" + mx. deleteMax (); System. out. println ("remaining heap:"); mx. printMaxHeapInTreeShape (); System. out. println ();}


Result:

1st delete: The deleted Value is: 15 remaining heap: 14 13 12 9 10 5 11 4 6 3 8 2 1 7 2nd delete: The deleted Value is: 14 remaining heap: 13 10 12 9 8 5 11 4 6 3 7 2 1 3rd delete: The deleted Value is: 13 the remaining heap is: 12 10 11 9 8 5 1 4 6 3 2 4th delete: The deleted Value is: 12 the remaining heap is: 11 10 5 9 8 2 1 4 6 3 7 5th delete: The deleted Value is: 11 the remaining heap is: 10 9 5 7 8 2 1 4 6 3 6th delete: the deleted heap value is 10. The remaining heap value is 9 8 5 7 3 2 1 4 6 7th. The deleted Value is 9. The remaining heap value is: 8 7 5 6 3 2 1 4 8th delete: The deleted Value is: 8 the remaining heap is: 7 6 5 4 3 1 9th delete: The deleted Value is: 7 remaining heap: 6 4 5 1 3 2 10th delete: The deleted Value is: 6 remaining heap: 5 4 2 1 3 11th delete: the deleted Value is: 5. The remaining heap is: 4 3 2 1 12th. The deleted Value is: 4. The remaining heap is: 3 1 2 13th. Delete: the deleted Value is: 3. The remaining heap is: 2. 14th delete: The deleted Value is: 2. The remaining heap is: 1. 15th delete: The deleted Value is: 1. The remaining heap is:


Conclusion:

Therefore, the largest heap is restored to the largest heap shape after each insertion/deletion, And the deletion order of the largest Heap has been sorted.

Our conclusion is also suitable for the minimum heap.

This article from "parallel line cohesion" blog, please be sure to keep this source http://supercharles888.blog.51cto.com/609344/1350358

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.