Skip to content

Commit

Permalink
Create heap in java (Asiatik#189)
Browse files Browse the repository at this point in the history
  • Loading branch information
kumaraguru16 authored and tstreamDOTh committed Oct 9, 2018
1 parent 8e707b8 commit 7ffd9e3
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions heap in java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
public class HeapSort {

private static int[] array = new int[]{5, 3, 6, 4, 8, 9 , 1, 10};

public static void main(String[] args) {
heapSort();

for(int i : array) {
System.out.println(i);
}
}

private static void heapSort() {
int length = array.length;

buildMaxHeap(array, length);
for(int i = length - 1; i > 0; i--) {
int temp = array[0];
array[0] = array[i];
array[i] = temp;
maxHeapify(array, 1, i);
}
}

private static void buildMaxHeap(int[] array, int heapSize) {
if(array == null) {
throw new NullPointerException("null");
}
if(array.length <=0 || heapSize <= 0) {
throw new IllegalArgumentException("illegal");
}
if(heapSize > array.length) {
heapSize = array.length;
}

for(int i = heapSize/2; i > 0; i--) {
maxHeapify(array, i, heapSize);
}
}

private static void maxHeapify(int[] array, int index, int heapSize) {
int l = index * 2;
int r = l + 1;
int largest;

if(l <= heapSize && array[l - 1] > array[index - 1]) {
largest = l;
} else {
largest = index;
}

if(r <= heapSize && array[r - 1] > array[largest - 1]) {
largest = r;
}

if(largest != index) {
int temp = array[index - 1];
array[index - 1] = array[largest - 1];
array[largest - 1] = temp;
maxHeapify(array, largest, heapSize);
}
}
}

0 comments on commit 7ffd9e3

Please sign in to comment.