Heap and Heapify

Source: Internet
Author: User
Tags throw exception

Recently review the data structure, and then go back to see Seishen courseware, see the realization of priorityqueue. Oneself also writes according to Seishen's code.

The following uses binary heap to implement a simple max-oriented priorityqueue.

  1. Here binary heap we are using array represetation, arrays form.
    1. The No. 0 element we leave empty, starting from the first element to store, the first element will be the largest element in the PQ.
    2. The feature is that if the parent node location is K, then the position of the two child nodes is 2 * k and 2 * k + 1. This is convenient to calculate, knowing that the parent node is easy to calculate child nodes, know the location of child nodes can immediately know the location of the parent node.
    3. The Max Heap obeys the Max heap order, which means that the parent node's value is always greater than or equal to the child node value. (But the parent node's sibling can be no greater than the child node value of the current parent node)
    4. The element is preferably implements comparable[], otherwise we will also write comparator<> ()
  2. At the beginning of the construction method, we used a fixed-length array for simplicity. Normally, you should use a resizing array, as well as a load factor.
    1. When load factor, that is, the number of elements N/array length len = 0.75, we expand the array by one time and then copy the previous element in
    2. When load factor < 0.25, we halved the array and copied the previous element.
  3. The main methods are insert (), Peek (), Delmax () and IsEmpty (), in order to test I also put in some other methods, such as shuffle (), heapify (), and Heapsort (), a little bit below to analyze each method.
    1. Insert (): Each time the element is added, we will first increase the number of elements in the PQ, that is, ++n, and then place the new element x in the new position in the array.  Next we call the swim () method to keep the PQ in order. Total complexity is O (LOGN)
    2. Swim (): The heap order is maintained up. We need a swim () operation on the value of this position when we find that the element in the array is not determined to conform to the Max heap order. Consider only child nodes and parent nodes, regardless of sibling.
      1. The main operation is to compare this child node with its parent node, if the value of the child node with K is greater than its parent node, we exchange these two nodes
      2. Continue comparing the swapped child nodes and their new parent nodes, which can be done with K/=.
      3. The traversal is performed under the conditions of K > 1. Since k > 1, K/2 is the largest of 1, which is our largest node
      4. Each time we insert we can use swim () to keep the heap order
    3. Peek (): We can directly return to the maximum node elements[1], note some boundary conditions, or the node does not exist when the throw exception
    4. Delmax (): Deleting the maximum node is a feature of max-heap. Total complexity O (LOGN)
        1. We first swap the nodes of the largest and last positions, use n--to reduce the number of elements N by 1, and place the maximum node position to null-elements[n + 1] = null. This avoids loitering and prevents the garbage collection mechanism from receiving this array.
        2. The element at this point where we are in the elements[1] position may not satisfy the max heap order, and we execute the sink () method for processing.
    5. Sink (): The heap order is maintained down. At this point we know that this element may not meet the Max heap order between its two child nodes. We compare the size between the parent node and the two child nodes at the time of judgment.
      1. Assuming the current parent node position is K, then two possible child nodes are 2 * k and 2 * k + 1. We must first determine whether the left child node exists, that is, 2 * k whether <= N
      2. In the presence of the left child node, we set J = 2 * k, next we determine whether the right child node exists, that is, whether J < N, if the right child node exists, we compare the size of the child node, and try to update the index value of the larger child node J
      3. Next we determine whether the larger child node is greater than the parent node value, if no, elements[j] < Elements[k], then we break directly
      4. Otherwise, we exchange K and J-swap (K, j), and update k = J to continue with the next level of sink
    6. IsEmpty (): PQ is empty, this is our direct judge whether N = = 0
    7. Swap (): Swap two nodes
    8. Shuffle (): Knuth shuffle is used here.   is to first create a random with seed and then iterate over the array to generate a pseudo-random number to swap with the current index. O (N)
    9. Heapify (): This refers to the maximum heapify. We only need to start with k = N/2, Sink K () under the condition of K >= 1, and then k--.
    10. Heapsort (): Heap sorting, here we first heapify () the array, and then the K > 1 under the conditions of each time the largest element exchange to the end of the arrays, and then the position of 1 elements sink. In-place O (NLOGN).

 Public classMAXPQ { Publicinteger[] elements;  Public intN;  PublicMAXPQ (intsize) {Elements=NewInteger[size + 1]; N= 0;//index starts with 1    }         Public voidInsert (Integer x) {elements[++n] =x;    Swim (N); }        Private voidSwimintk) { while(k > 1 && elements[k] > ELEMENTS[K/2]) {swap (k, K/2); K/= 2; }    }         Publicinteger Delmax () {integer Max= Elements[1]; Swap (1, n--); Elements[n+ 1] =NULL; Sink (1); returnMax; }        Private voidSinkintk) { while(2 * k <=N) {intj = 2 *K; if(J < N && Elements[j] < Elements[j + 1]) {J++; }            if(Elements[j] <Elements[k]) {                 Break;            } swap (k, j); K=J; }    }         PublicInteger Peek () {returnElements[1]; }         Public BooleanIsEmpty () {returnN = = 0; }        Private voidSwapintIintj) {Integer tmp=Elements[i]; Elements[i]=Elements[j]; ELEMENTS[J]=tmp; }         Public voidShuffle () {//For testingJava.util.Random Rand =NewJava.util.Random (System.currenttimemillis ());  for(inti = 1; I <= N; i++) {            intR = 1 +Rand.nextint (i);        Swap (I, r); }            }         Public voidHeapify () {//For testing         for(intK = N/2; K >= 1; k--) {sink (k); }    }         Public voidHeapsort () {heapify (); intn =N;  while(N > 1) {Swap (1, n--); Sink (1); }    }}

Above is a binary heap design for a max-oriented priority Queue, array is 1-based.  If meet the interviewer to ask how heapify how to do? Here we will make a few changes to the above code, into 0-based, can be directly max-heapify the array.

    1. Heapify () Method: we can see that our heapify method basically has not changed, except to turn N/2 into the length of the array nums.length/2
    2. Sink () Method: Here we have to look at the boundary conditions. Set len = Nums.length, where Len is equivalent to the previous n, and then compare, we have to subtract each J 1, from 1-based to 0-based, no other code need to change

     Public Static voidHeapify (int[] nums) {        if(Nums = =NULL) {            return; }         for(intK = NUMS.LENGTH/2; K >= 1; k--) {sink (nums, k); }    }        Private Static voidSinkint[] Nums,intk) {intLen =nums.length;  while(2 * k <=Len) {            intj = 2 *K; if(J < Len && Nums[j-1] <Nums[j]) {J++; }            if(Nums[k-1] > Nums[j-1]) {                 Break; } swap (Nums, K-1, J-1); K=J; }    }        Private Static voidSwapint[] Nums,intIintj) {intTMP =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=tmp; }

Test Client:

 Public Static voidMain (string[] args) {intLen = 10; int[] Nums =New int[Len];  for(inti = 0; i < Len; i++) {Nums[i]= i + 1;                } shuffle (Nums);  for(inti:nums) {System.out.print (i+ " ");        } heapify (Nums);                System.out.println ();  for(inti:nums) {System.out.print (i+ " "); }    }    

Reference:

http://algs4.cs.princeton.edu/24pq/

Heap and Heapify

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.