java实现:
public class 堆排序 {
public static void main(String[] args) {
int A[] = {0,13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
heap_Sort(A);
for (int i = 1; i < A.length; i++) {
System.out.print(A[i] + " ");
}
}
// public static void swap(int a, int b) {
// int temp = a;
// a = b;
// b = temp ;
// }
//
public static int parent(int i) {
return i/2;
}
public static int left_child(int i) {
return i * 2;
}
public static int right_child(int i) {
return 2*i + 1;
}
public static void Max_Heapify(int A[], int i, int Heap_size) {
int l = left_child(i);
int r = right_child(i);
int largest ;
if (l <= Heap_size && A[l] > A[i]) {
largest = l;
}
else {
largest = i ;
}
if (r <= Heap_size && A[r] > A[largest]) {
largest = r;
}
if (largest != i) {
// swap(A[i], A[largest]);
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
Max_Heapify(A, largest, Heap_size);
}
}
public static void Build_Max_Heap(int A[]) {
int heap_size = A.length - 1;
for (int i = A.length/2; i >= 1 ; i--) {
Max_Heapify(A, i, heap_size);
}
}
public static void heap_Sort(int A[]) {
Build_Max_Heap(A);
int HeapSize = A.length - 1;
for (int i = A.length - 1; i >= 2 ; i--) {
// swap(A[i], A[1]);
int temp = A[i];
A[i] = A[1];
A[1] = temp;
HeapSize --;
Max_Heapify(A, 1, HeapSize);
}
}
}