public static void heapsort(int[] a) { int len = a.length; //构建堆 for(int i = len / 2 - 1;i >= 0 ;i-- ) { heapadjust(a,i,len - 1); } for(int j=len -1;j>0;j--) { int temp = a[0]; a[0] = a[j]; a[j] = temp; heapadjust(a,0,j-1); } } public static void heapadjust(int[] a,int pos,int len) { int child = 2 * pos + 1; int tmp = a[pos]; while(child <= len) { if(child <len && a[child] < a[child + 1]) { child ++; } if(a[child] >tmp) { a[pos] = a[child]; pos = child; child = 2*pos + 1; } else { break; } } a[pos] = tmp; } public static void main(String[] args) { int[] array = { 49, 38, 65, 97, 76, 13, 27, 50 }; for(int i : array) { System.out.print(i + " "); } heapsort(array); System.out.println(); for(int i = 0;i<array.length;i++) { System.out.print(array[i] + " " ); } }