public class HeapSort {
public static void main(String[] args) {
int a[] = {1,2,3,4,5,6,7,8,9,11,10,13,12,11,10};
heapsort(a);
for(int b :a)
System.out.println(b);
}
public static void heapsort(int[] a){
int temp;
int currRoot = 0;
buildmaxHeap(a);
int heapSize = a.length-1;
for(int i = a.length-1;i>0;i--) {
temp = a[i];
a[i] = a[0];
a[0] = temp;
heapSize--;
maxHeapify(a,currRoot,heapSize);
}
}
public static void buildmaxHeap(int[] a){
for(int i = (int) Math.ceil((a.length-1)/2); i>=0;i--)
maxHeapify(a,i,a.length-1);
}
public static void maxHeapify(int[] a,int currRootIndex,int heapSize) {
int largest,temp;
int leftIndex = 2* currRootIndex + 1;
int rightIndex = 2* currRootIndex + 2;
if(leftIndex <= heapSize && a[leftIndex] > a[currRootIndex])
largest = leftIndex;
else
largest = currRootIndex;
if(rightIndex <= heapSize && a[rightIndex] > a[largest])
largest = rightIndex;
if(largest != currRootIndex){
temp = a[currRootIndex];
a[currRootIndex] = a[largest];
a[largest] = temp;
maxHeapify(a, largest, heapSize);
}
}
}
No comments:
Post a Comment