不多逼逼,贴代码。
package sort;
public class HeapSort {
public static void heapSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
buildheap(arr, i);
}
for (int n = arr.length - 1; n > 0; n--) {
swap(arr, 0, n);
heapPro(arr, n);
}
}
public static void heapPro(int[] arr, int n) {
int leftChildIndex = 1;
for (int i = 0; leftChildIndex < n;) {
if (leftChildIndex != n - 1 && arr[leftChildIndex] < arr[leftChildIndex + 1]) {
leftChildIndex++;
}
if (arr[i] < arr[leftChildIndex]) {
swap(arr, leftChildIndex, i);
i = leftChildIndex;
leftChildIndex = 2 * i + 1;
} else {
break;
}
}
}
public static void buildheap(int[] arr, int i) {
for (; i > 0;) {
if (arr[i] > arr[(i - 1) / 2]) {
swap(arr, i, (i - 1) / 2);
} else {
break;
}
i = (i - 1) / 2;
}
}
public static void swap(int[] arr, int i, int j) {
int help = arr[i];
arr[i] = arr[j];
arr[j] = help;
}
public static void main(String[] args) {
int[] arr = new int[] { 1, 5, 3, 9, 6, 2, 7, 4, 8 };
heapSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
}