Advertisement
gelita

heapify

Mar 13th, 2020
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.69 KB | None | 0 0
  1. // package whatever; // don't place package name!
  2. /*
  3. subset of binary trees.
  4. min or max heap.
  5.  
  6.         1
  7.       /   \
  8.       2   3
  9.     /   \  / \
  10.     4   5  6  7
  11.     /
  12.     8
  13.    
  14.     0
  15.     /\
  16.     1 2
  17.     /\  /\
  18.     3 4 5 6
  19.    
  20.  
  21.   Tree implementation:
  22.   insert: O(log n) - O(n)
  23.   deletion: O(n)
  24.  
  25.   Array: [0,1,2,3,4,5,6]
  26.   insert: O(1)
  27.   deletion: O(n)
  28.   bubbleup:
  29.   bubble down: swap with the smaller child
  30.   insert: O(log(n))
  31.   deletion
  32.  
  33.   left child : p = (c - 1) / 2
  34.   right child : p = (c - 2) / 2
  35.   left child : c = p * 2 + 1
  36.   right child : c = p * 2 + 2
  37.  
  38.   heapify:
  39.  
  40.   [5,3,2,8,1,4,6]
  41.  
  42.      5
  43.     / \
  44.     3  2
  45.     / \ / \
  46.     8 1 4 6
  47.  
  48.  
  49.    /
  50.    6
  51.    / \
  52.    x  x
  53.  
  54.  
  55.  
  56.  
  57.  
  58.   [8,5,6,4,2,1]
  59.  
  60.   8
  61.   / \
  62.   5  6
  63.   / \ /
  64.   4 2 1
  65.  
  66.  
  67.  
  68.  
  69.  
  70. */
  71.  
  72. import java.io.*;
  73. import java.util.*;
  74.  
  75. class MyCode {
  76.     public static void main (String[] args) {
  77.     int[] in = new int[]{5,3,2,8,1,4,6};
  78.         System.out.println(Arrays.toString(Heap.heapify(in)));
  79.     }
  80. }
  81. class Heap {
  82.   public static int[] heapify(int[] in){
  83.     for ( int i = in.length - 1; i >= 0; i--){
  84.       in = bubbledown(in,i);
  85.     }
  86.     return in;
  87.   }
  88.   public static int[] bubbledown(int[] in,int p){
  89.     int c = childOf(in,p);
  90.     while (c < in.length && in[c] > in[p]){
  91.       int temp = in[c];
  92.       in[c] = in[p];
  93.       in[p] = temp;
  94.       p = c;
  95.       c = childOf(in,p);
  96.     }
  97.     return in;
  98.   }
  99.   public static int childOf(int[] in,int p){
  100.     int leftC = p * 2 + 1;
  101.     if (leftC >= in.length || in[leftC] > in[leftC + 1]){
  102.       return leftC;
  103.     }
  104.     return leftC + 1;
  105.   }
  106. }
  107. /*
  108.       8
  109.     /   \
  110.     5    6
  111.     / \  /\
  112.     3  1 4 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement