package test;
public class HeapSort {
public static void main(String[] args) {
int[] arr = {10,9,8,7,6,5,4,3,2,1};
System.out.print("排序前;");
printArr(arr);
System.out.println();
sort(arr);
System.out.println("排序后:");
printArr(arr);
}
private static void sort(int[] arr) {
for (int i = arr.length / 2; i >= 0; i--) { // 构建堆;
heapSort(arr, i, arr.length - 1);
}
for (int i = arr.length - 1; i >= 0; i--) {
int tmp = arr[0];
arr[0] = arr[i];
arr[i] = tmp;
heapSort(arr, 0, i - 1);
}
}
/**
* 构建堆和调整堆;
*
* @param arr
* @param s
*/
public static void heapSort(int[] arr, int s, int m) {
int tmp = arr[s];
int i;
for (i = 2 * s+1; i <= m; i = i * 2+1) {
if (i < m && arr[i] < arr[i + 1]) {
i++;
}
if (tmp <arr[i]) {
arr[s] = arr[i];
s =i;
}else {
break;
}
}
arr[s] = tmp;
}
/**
* 打印;
* @param arr
*/
private static void printArr(int[] arr) {
for(int i:arr) {
System.out.print(i+" ");
}
}
}