标签:
public class HeapSort {
/**
* 堆排序
*
* @param args
*/
public static void heapOne(int[] a, int n, int k) {
int left = 2 * k + 1;
int right = 2 * k + 2;
int a1 = Integer.MAX_VALUE;
int a2 = Integer.MAX_VALUE;
if (left >= n && right >= n) return;
if (left < n) a1 = a[left];
if (right < n) a2 = a[right];
if (a1 >= a[k] && a2 >= a[k]) return;
if (a1 < a2) {
int temp = a[k];
a[k] = a[left];
a[left] = temp;
heapOne(a, n, left);
} else {
int temp = a[k];
a[k] = a[right];
a[right] = temp;
heapOne(a, n, right);
}
}
public static void heapSort(int[] array) {
// 创建初始堆
for (int i = ((array.length - 1) / 2); i >= 0; i--) {
heapOne(array, array.length, i);
}
int n = array.length;
while (n > 0) {
System.out.print(array[0]);
if (n > 1) {
System.out.print(",");
}
array[0] = array[n - 1];
n--;
heapOne(array, n, 0);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1 };
heapSort(a);
}
}
标签:
原文地址:http://www.cnblogs.com/wllearnandroid/p/4699015.html