Dynamic operation of the heap (insert, delete, adjust)

Source: Internet
Author: User

The heap has the largest heap and the smallest heap, and the largest heap is the complete binary tree where the value of each node >= its left and right children (if any). The smallest heap is the complete binary tree where the value of each node <= its left and right child values.

A sequence with n elements {k1,k2,..., kn} is called a heap if and only if the following relationships are met.


The three basic operations of the heap (the following are examples of the maximum heap):
⑴ Maximum heap insertion

In order to maintain the shape of the complete binary tree, the node x to be inserted first is placed at the far right of the bottom, and after insertion satisfies the characteristics of the complete binary tree;
Then the x is adjusted upward to the appropriate location to meet the nature of the heap, for example, insert 80, first put 80 at the end, and then two times to the appropriate position.
Time: O (LOGN). "The knot is floating."


Program implementation:
<span style= "FONT-SIZE:18PX;"        >//inserting elements into the largest heap, heap: The array that holds the heap elements public static void insert (list<integer> heap, int value) {//At the end of the array is added         if (Heap.size () ==0) heap.add (0);//The position of the array subscript 0 does not place the element Heap.add (value);         Start ascent operation//HeapUp2 (heap, Heap.size ()-1);      Heapup (Heap, Heap.size ()-1);          }//Rise, let the number of insertions and the value of the parent node be compared, when the parent node is larger than the values of the Exchange public static void Heapup (list<integer> heap, int index) {  Note that since the value is starting from subscript 1, when index = 1, it is already the root node if (Index > 1) {//Find out the father's node int parent = Index              /2;             Gets the numeric value of the corresponding position int parentvalue = (Integer) heap.get (parent);             int indexvalue = (Integer) heap.get (index); If the Father node is smaller than the value of index, Exchange the value if (Parentvalue < Indexvalue) {//Exchange value Swap (hea                 p, parent, index);             Recursive invocation of Heapup (heap, parent); }}} </span>


⑵ delete  
   operation principle: When you delete the value of a node, The original position will appear a hole, the way to fill the hole is,  
assigns the value of the last leaf to the hole and cuts it to the appropriate position, finally removing the leaf.  
  
To delete 72, replace 72 with the last element in the heap, 35 to the appropriate position, and then delete the leaf node.  
"node sinking" &NBSP;

 

<span style= "FONT-SIZE:18PX;" > Program:/** * Delete the node in the heap where the position is index * Operation principle is: when the value of the node is deleted, the original position will appear a hole * The method of filling this hole is to assign the value of the last leaf to the hole and finally delete the leaf @param Heap */public static void Delete (List<integer> Heap,int index) {//assigns the value of the last leaf to the index position h         Eap.set (Index, Heap.get (Heap.size ()-1));         Sinking Operation//heapdown2 (heap, index);         Heapdown (heap, index);     Remove the number from the last position Heap.remove (Heap.size ()-1); }/** * Recursive implementation * When you delete a data in the heap, depending on the nature of the heap, the corresponding position should be moved down to keep the heap property unchanged * @param heap keep An array of heap elements * @param index deleted node Location */public static void Heapdown (list<integer> heap, int index) {//Because the first position is stored in a null value, not within the consideration I          NT n = heap.size ()-2;          Record the position of the largest son of the node int child =-1;         2*index>n indicates that the node has no left and right son node, then return if (2 * index > N) {return;          }//If both the left and right sons are present else if (2 * Index < N) {//define the right son node child = 2 * index;   If the left son small less right operand son's value, take the right son's subscript 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)) {//Swap the value of child in heap, and index position              Swap (heap, child, index);         After completion of the exchange recursive call, continue to descend Heapdown (heap, child); }} </span>


⑶ initialize  
Method 1: Insert method:  
  Start with an empty heap and insert each node in turn until all nodes are inserted into the heap.  
  Time: O (N*log (n))  
  Method 2: Adjustment method:  
    sequence corresponds to a complete binary tree; from the last branch node (n Div 2) Start, up to the root (1), adjust (sink) each branch node in turn,
to form a heap that is rooted at each branch node, and when the root node is finally adjusted, the entire tree becomes a heap.  
  Time: O (n)  
The sequence of pairs, to make it a heap, we start with the last branch node (10/2), whose value is 72, and sequentially adjust (sink) Each branch node 53,18,36 45.  
 
 
 

<span style= "FONT-SIZE:18PX;"        > Program:/* Build the heap according to the nature of the tree, the first half of the tree node must be a branch node, that is, there are children, so we start from here 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); }/** * Adjust the heap so that it satisfies the heap definition * @param i * @param n */public static void adjust (list<integer> he          Ap,int I, int n) {int child; for (; I <= n/2;)              {Child = i * 2;              if (Child+1<=n&&heap.get (child) 

(4) Maximum heap sorting

<span style= "FONT-SIZE:18PX;" >//Sort public    static void Heapsort (List<integer> heap) {for                 (int i = Heap.size ()-1; i > 0) on one of the largest heap heaps; i--) {           /* Swap the root node with the last element and adjust the remaining n-1 nodes to arrange the order *              /swap (heap,1, i);              Adjust (heap,1, i-1);          }      }  </span>


(5) Complete code
<span style= "FONT-SIZE:18PX;"  >import java.util.*; /** * Maximum heap insertion and deletion operation implemented * @author Arthur */public class Heap {/** * Delete the value in the heap where position is index * Operation principle is: when the value of the node is deleted, the original position will appear The way a hole fills this hole is to assign the value of the last leaf to the hole and finally delete the leaf * @param heap a maximum heap */public static void Delete (List<integer&gt ;         Heap,int index) {//assigns the value of the last leaf to the index position heap.set (index, Heap.get (Heap.size ()-1));         Sinking Operation//heapdown2 (heap, index); Heapdown (heap, index);     Node sinking//The number of the last position is removed Heap.remove (heap.size ()-1); /** * Node sink recursive implementation * When deleting a data from a heap, the corresponding position should be moved down in order to keep the heap property unchanged * @param heap to keep the maximum heap elements of the stack * @param ind The location of the ex-deleted node */public static void Heapdown (list<integer> heap, int index) {///because the first location stores a null value and is not considered          Inside int n = heap.size ()-2;          Record the position of the largest son of the node int child =-1;         2*index>n indicates that the node has no left and right son node, then return if (2 * index > N) {return; }//If the left and right sons arePresence else if (2 * Index < N) {//define left son node child = 2 * index; If the left son small less right operand son's value, take the right son's subscript if ((integer) heap.get (Child) < (integer) heap.get (child + 1)) {CH             ild++;         }}//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)) {//Swap the value of child in heap, and index position              Swap (heap, child, index);         After completion of the exchange recursive call, continue to descend Heapdown (heap, child); }}//non-recursive implementation public static void HeapDown2 (list<integer> heap, int index) {Int. Child = 0;//Store left son         The position of int temp = (Integer) heap.get (index);         int n = heap.size ()-2;             If there is a son, for (; 2 * index <= n; index = child) {//Gets the position of the left son = 2 * index;            If only the left son if (child = = N) {children = 2 * index; }//If the right son is greater than the left son's value else if ((integer) heap.get (Child) < (integer) Heap.get (children + 1)) {CH             ild++; }//If the value of the largest son is greater than that of the temp if ((Integer) heap.get (child) >temp) {//swap the child in the heap, and IND             Ex position value swap (heap, child, index);             } else {break;  }}}//Print the list 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 value of the B position 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);          Assigns the value of index to child's position heap.set (A, heap.get (b));     Assigns the value of the original child position to the index position heap.set (b, temp); }//Inserts elements into the maximum heap public static void Insert (list<integer> heap, int value) {//At the end of the arrayAdd the element to be inserted if (Heap.size () ==0) heap.add (0);//The position of the array subscript 0 does not place the element Heap.add (value);         Start ascent operation//HeapUp2 (heap, Heap.size ()-1);      Heapup (Heap, Heap.size ()-1);          }//The node floats, allowing the number of insertions to be compared to the parent node, and when the parent node is greater than the value of the node Exchange public static void Heapup (list<integer> heap, int index) { Note that since the value is from the beginning, when index = 1, the root node is already the IF (Index > 1) {//Save the Father's node int parent = Inde              X/2;             Gets the numeric value of the corresponding position int parentvalue = (Integer) heap.get (parent);             int indexvalue = (Integer) heap.get (index); If the Father node is smaller than the value of index, Exchange the value if (Parentvalue < Indexvalue) {//Exchange value Swap (hea                 p, parent, index);             Recursive invocation of Heapup (heap, parent);  }}}//non-recursive implementation public static void HeapUp2 (list<integer> heap, int index) {int parent =         0; for (; index > 1; index/= 2) {//GetSubscript parent = Index/2 of the parents of index;             Gets the value of the parent node int parentvalue = (Integer) heap.get (parent);                          Gets the value of the index position int indexvalue = (Integer) heap.get (index);             If less than on swap if (Parentvalue < Indexvalue) {swap (heap, parent, index); }}}/* Build the heap according to the nature of the tree, the first half of the tree node must be a branch node, i.e. there are children, so we start from here to adjust the initial heap */public static void adjust (List<integer&gt ;                    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); }/** * Adjust the heap so that it satisfies the heap definition * @param i * @param n */public static void adjust (list<integer> he          Ap,int I, int n) {int child; for (; I <= n/2;)              {Child = i * 2; if (child+1<=n&&Heap.get (Child) 

Program run:
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 the heap is sorted:
2 3 5 7 8 9 10 11 15 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

Dynamic operation of the heap (insert, delete, adjust)

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.