public class HeapSort { public static void main(String[] args) { HeapSort sort = new HeapSort(); int[] a = {2,4,3,1,0,9,5,6,3,7}; sort.sort(a); for(int i = 0 ; i < a.length ; i++){ System.out.println(a[i]); } } private void maxHeapify(int[] a,int i,int length){ int left = left(i); int right = right(i); int max = a[i]; int index = i; if(left < length && max < a[left]){ max = a[left]; index = left; } if(right < length && max < a[right]){ max = a[right]; index = right; } if(index != i){ a[i]^=a[index]; a[index]^=a[i]; a[i]^=a[index]; maxHeapify(a,index,length); } } private void buildMaxHeap(int[] a){ for(int i = a.length / 2 - 1 ; i >= 0 ; i--){ maxHeapify(a,i,a.length); } } private void sort(int[] a){ buildMaxHeap(a); for(int i = a.length - 1 ; i >= 0 ; i--){ if(i != 0){ a[i]^=a[0]; a[0]^=a[i]; a[i]^=a[0]; } maxHeapify(a,0,i); } } private int left(int i){ return i*2; } private int right(int j){ return j*2+1; } }