Max heap insert/delete/adjust/sort (illustration + program) (JAVA)

Source: Internet
Author: User
A heap can be divided into a maximum heap and a minimum heap. The maximum heap is a complete binary tree with the value of> = its left and right children (if any. The minimum heap is the Complete Binary Tree with the value of <= its left and right child values for each node.

The sequence of n elements {k1, k2,..., kn} is called heap only when and only when the following relations are met.
 

Three basic operations on the heap (the largest heap is used as an example below ):
(1) Insert the maximum heap

To maintain the form of A Complete Binary Tree, you must first place the node x to be inserted on the rightmost right of the bottom layer, and then insert it to the full binary tree;
Then, adjust x to the appropriate position in sequence to meet the nature of the heap. For example, insert 80 in the middle, put 80 at the end, and then go up to the appropriate position twice.
Time: O (logn ). "Node floating"
 

Program Implementation:

// Insert an element into the maximum heap. heap: the array storing heap elements: public static void insert (List <Integer> heap, int value) {// Add if (heap. size () = 0) heap. add (0); // the position where the subscript of the array is 0 without the Element heap. add (value); // start the upstreaming operation // heapUp2 (heap, heap. size ()-1); heapUp (heap, heap. size ()-1);} // rises to compare the number of inserts with the value of the parent node, when the value is greater than the parent node, public static void heapUp (List <Integer> heap, int index) is exchanged with the value of the parent node) {// note that because the value starts from the subscript of 1, when index = 1, it is already the root node if (index> 1) {// obtain the parent node int parent = index/2; // obtain the corresponding position value int parentValue = (Integer) heap. get (parent); int indexValue = (Integer) heap. get (index); // if the Father's Day point is smaller than the index value, the value of the two is exchanged if (parentValue <indexValue) {// swap (heap, parent, index); // recursively call heapUp (heap, parent );}}}

(2) Delete
The operation principle is: when the node value is deleted, a hole will appear in the original position. The method to fill the hole is,
The final leaf value is assigned to the hole and lowered to the proper position. Finally, the leaf is deleted.

To delete 72, replace 35 with 72 with the last element in the heap, then sink 35 to the appropriate position, and finally Delete the leaf node.
"Sink node"

 

Program:/*** Delete the node with the index position in the heap * Operation Principle: when the value of the node is deleted, in the original position, a hole * is filled by assigning the value of the final leaf to the hole, delete the leaf * @ param heap */public static void delete (List <Integer> heap, int index) {// assign the value of the last leaf to the index location heap. set (index, heap. get (heap. size ()-1); // sink operation // heapDown2 (heap, index); heapDown (heap, index); // Delete the number in the last position heap. remove (heap. size ()-1);}/** Recursive Implementation * When deleting a data in the heap, the corresponding position should be moved down according to the heap nature, to keep the heap unchanged * @ param heap keep the array of heap elements * @ param index the location of the deleted node */public static void heapDown (List <Integer> heap, int index) {// because the first location stores null values, int n = heap is not considered. size ()-2; // record the location of the largest son node int child =-1; // 2 * index> n indicates that the node has no left or right son node, then return if (2 * index> n) {return;} // if both the left and right sons have else if (2 * index <n) {// define the left son node child = 2 * index; // if the left son is smaller than the right son value, take the subscript of the right son if (Integer) heap. get (child) <(Integer) heap. get (child + 1) {child ++ ;}// if there is only one son (left son node) else if (2 * index = n) {child = 2 * index;} if (Integer) heap. get (child)> (Integer) heap. get (index) {// switch the child in the heap and the value swap (heap, child, index) at the index position; // recursive call after the switch is completed, continue to decline heapDown (heap, child );}}

(3) initialization
Method 1: insert method:
From the empty heap, insert each node in sequence until all nodes are inserted to the heap.
Time: O (n * log (n ))
Method 2: adjustment method:
The sequence corresponds to a Complete Binary Tree. Each branch node is adjusted (sunk) sequentially from the last branch node (n div 2) to the root (1 ),
In order to form a heap with each branch node as the root, when the root node is adjusted, the entire tree becomes a heap.
Time: O (n)
To make it a heap, we start from the last branch node (10/2) with a value of 72, which is for each branch node, 36 45 adjustment (sinking ).
 
 
 

Program:/* build a heap based on the nature of the tree. The first half of the Tree node must be a branch node with children, so from here we start to adjust the initial heap */public static void adjust (List <Integer> heap) {for (int I = heap. size ()/2; I> 0; I --) adjust (heap, I, heap. size ()-1); System. out. println ("========================================== ============ "); system. out. println ("adjusted initial heap:"); print (heap) ;}/ *** adjusted the heap, make it meet the defined heap * @ param I * @ param n */public static void adjust (List <Integer> heap, int I, int n) {int child; (; I <= n/2;) {child = I * 2; if (child + 1 <= n & heap. get (child) 

(4) Maximum heap sorting

// Sort a maximum heap by public static void heapSort (List <Integer> heap) {for (int I = heap. size ()-1; I> 0; I --) {/* swap the root node with the last element and adjust the remaining n-1 nodes, you can sort the Order */swap (heap, 1, I); adjust (heap, 1, I-1 );}}

(5) complete code

Import java. util. *; /*** maximum Heap insert and delete operations * @ author Arthur */public class Heap {/*** Delete the value at the index position in the Heap * operation principle is: when you delete the value of a node, a hole * fills the hole in the original position by assigning the value of the final leaf to the hole, finally, delete the leaf * @ param heap a maximum heap */public static void delete (List <Integer> heap, int index) {// assign the value of the last leaf to the index location heap. set (index, heap. get (heap. size ()-1); // Sinking Operation // heapDown2 (heap, index); heapDown (heap, index ); // sink the node // Delete the number in the last position from the heap. remove (heap. size ()-1);}/*** Recursive Implementation of node sinking * When deleting data in a heap, the corresponding position should be moved down according to the heap nature, in order to keep the heap unchanged * @ param heap the array of the maximum heap elements * @ param index the location of the deleted node */public static void heapDown (List <Integer> heap, int index) {// because the first location stores null values, int n = heap is not considered. size ()-2; // record the location of the largest son node int child =-1; // 2 * index> n indicates that the node has no left or right son node, then return if (2 * index> n) {return;} // if both the left and right sons have else if (2 * index <n) {// define the left son node child = 2 * index; // if the left son is smaller than the right son value, take the subscript of the right son if (Integer) heap. get (child) <(Integer) heap. get (child + 1) {child ++ ;}// if there is only one son (left son node) else if (2 * index = n) {child = 2 * index;} if (Integer) heap. get (child)> (Integer) heap. get (index) {// switch the child in the heap and the value swap (heap, child, index) at the index position; // recursive call after the switch is completed, continue to decrease heapDown (heap, child) ;}// non-recursive public static void heapDown2 (List <Integer> heap, int index) {int child = 0; // store the left son location int temp = (Integer) heap. get (index); int n = heap. size ()-2; // if you have a son, for (; 2 * index <= n; index = child) {// obtain the left son's position, child = 2 * index; // if only the left son if (child = n) {child = 2 * index;} // if the right son is greater than the left son value, else if (Integer) heap. get (child) <(Integer) heap. get (child + 1) {child ++;} // if the son with the largest value is greater than the value of temp, if (Integer) heap. get (child)> temp) {// switch the child in the heap and the value swap (heap, child, index) at the index position;} else {break ;}}} // print the public static void print (List <Integer> list) {for (int I = 1; I <list. size (); I ++) {System. out. print (list. get (I) + "");} System. out. println ();} // swap the values at the positions a and B in the heap with the public static void swap (List <Integer> heap, int a, int B) {// temporarily store the value of the child location int temp = (Integer) heap. get (a); // assign the index value to the heap location of the child. set (a, heap. get (B); // assign the value of the original child location to the index location heap. set (B, temp);} // insert the public static void insert (List <Integer> heap, int value) element into the max heap) {// Add the element if (heap. size () = 0) heap. add (0); // the position where the subscript of the array is 0 without the Element heap. add (value); // start the upstreaming operation // heapUp2 (heap, heap. size ()-1); heapUp (heap, heap. size ()-1);} // The Node goes up to compare the number of inserts with the value of the parent node, when the value is greater than the parent node, public static void heapUp (List <Integer> heap, int index) is exchanged with the node value {// note that because the value is marked as a small value, when index = 1, it is already the root node if (index> 1) {// Save the parent node int parent = index/2; // obtain the value int parentValue = (Integer) heap at the corresponding position. get (parent); int indexValue = (Integer) heap. get (index); // if the Father's Day point is smaller than the index value, the value of the two is exchanged if (parentValue <indexValue) {// swap (heap, parent, index); // recursively call heapUp (heap, parent) ;}}// non-recursively implement public static void heapUp2 (List <Integer> heap, int index) {int parent = 0; for (; index> 1; index/= 2) {// subscript parent = index/2 for the parent node that obtains the index; // obtain the value of the parent node int parentValue = (Integer) heap. get (parent); // obtain the index position value int indexValue = (Integer) heap. get (index); // if the value is smaller than the value, if (parentValue <indexValue) {swap (heap, parent, index) ;}}/ * creates a heap based on the nature of the tree, the first half of a tree node must be a branch node, that is, a child node. Therefore, we can adjust the initial heap */public static void adjust (List <Integer> heap) from here) {for (int I = heap. size ()/2; I> 0; I --) adjust (heap, I, heap. size ()-1); System. out. println ("========================================== ============ "); system. out. println ("adjusted initial heap:"); print (heap) ;}/ *** adjusted the heap, make it meet the defined heap * @ param I * @ param n */public static void adjust (List <Integer> heap, int I, int n) {int child; (; I <= n/2;) {child = I * 2; if (child + 1 <= n & heap. get (child) 

Program running:
D: \ java> java Heap
========================================================== ==========
Adjusted initial heap:
20 17 16 15 9 15 11 1 10 3 2 7 8 5
After Deletion
20 17 16 15 9 15 11 5 10 3 2 7 8
99 17 20 15 9 15 16 5 10 3 2 7 8 11
After sorting the heap:
2 3 5 7 8 9 10 11 15 16 17 20 99
-------------------------
20 17 16 10 15 9 15 0 5 2 11 1 7 3 8
====================================
========================================================== ==========
Adjusted initial heap:
93 72 48 53 45 30 18 36 15 35
93 80 48 53 72 30 18 36 15 35 45
93 72 48 53 45 30 18 36 15 35
93 53 48 36 45 30 18 35 15

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.