堆排序实现
public class Heap {
private static int heapSize = 0;
public static void MAX_HEAPIFY(int[] A, int i) {
int l = 2 * i ;
int r = 2 * i + 1;
int largest = 0;
if (l <= heapSize && A[l-1] > A[i-1]) {
largest = l;
} else {
largest = i;
}
if (r <= heapSize && A[r-1] > A[largest-1]) {
largest = r;
}
if (largest != i) {
int temp = A[i-1];
A[i-1] = A[largest-1];
A[largest-1] = temp;
MAX_HEAPIFY(A, largest);
}
}
public static void Build_MAX_HEAPIFY(int[] A) {
heapSize = A.length;
int half =A.length / 2;
for (int i = half; i > 0; i--) {
MAX_HEAPIFY(A, i);
}
// for(int j=0,leg=A.length; j<leg; j++){
// System.out.println(A[j]);
// }
}
public static void HEAPSORT(int[] A) {
Build_MAX_HEAPIFY(A);
for (int i = A.length; i >1; i--) {
int temp = A[0];
A[0] = A[i-1];
A[i-1] = temp;
heapSize--;
MAX_HEAPIFY(A, 1);
}
}
public static void main(String[] args) {
int[] a = { 17, 8, 45, 84, 2, 94 };
HEAPSORT(a);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}