1 public class MyHeapSort { 2 3 private static void OutPrint(int nums[]) 4 { 5 for(int i:nums) 6 System.out.print(i+" "); 7 System.out.println(); 8 } 9 public static void main(String[] args) { 10 int numbers[]=new int[]{1,5,2,7,4,2,8,34}; 11 OutPrint(numbers); 12 HeapSort(numbers); 13 OutPrint(numbers); 14 } 15 private static void HeapSort(int[] numbers) { 16 buildHeap(numbers); //建堆 17 for(int i=numbers.length-1;i>0;i--) //交换 18 { 19 int temp=numbers[0]; 20 numbers[0]=numbers[i]; 21 numbers[i]=temp; 22 23 adjustHeap(numbers,0,i); 24 } 25 } 26 private static void adjustHeap(int[] numbers, int i, int size) { //调整 27 28 int j=i*2+1; //左孩子节点 29 while(j<size) 30 { 31 if(j+1<size&&numbers[j]<numbers[j+1]) 32 j++; 33 if(numbers[i]<numbers[j]) //孩子节点大于父亲节点 34 { 35 int temp=numbers[i]; 36 numbers[i]=numbers[j]; 37 numbers[j]=temp; 38 i=j; 39 } 40 else 41 break; 42 j=2*i+1; //深入下去 43 } 44 45 } 46 private static void buildHeap(int[] numbers) { 47 for(int i=numbers.length/2-1;i>=0;i--) 48 { 49 adjustHeap(numbers,i,numbers.length); 50 } 51 } 52 53 }