import java.util.Arrays;
public class HeapSort {
public static void heapSort(int[] data) {
if (data.length <= 1)
return;
creatHeap(data);
System.out.println(Arrays.toString(data));
for (int i = data.length - 1; i > 0; i--) {
int temp = data[i];
data[i] = data[0];
data[0] = temp;
fixDown(data, 0, i - 1);
}
}
public static void creatHeap(int[] data) {
int i = data.length - 1;
int father = (i - 1) / 2;
for (int m = father; m >= 0; m--)
fixDown(data, m, data.length - 1);
}
public static void fixDown(int[] data, int i, int n) {
int j = i;
int cur = data[j];
int son = j * 2 + 1;
while (son <= n) {
if (son + 1 <= n && data[son + 1] > data[son])
son++;
if (cur > data[son])
break;
data[j] = data[son];
j = son;
son = j * 2 + 1;
}
data[j] = cur;
}
public static void main(String[] args) {
// 测试heapSort
// int[] data = { 5, 4, 3, 2, 1 };
int[] data = { 2, 3, 1, 5, 4, 8, 6, 7, 3, 8, 9, 1 };
// int[] data = { 15, 13, 1, 5, 20, 12, 8, 9, 11 };
// int[] data = { 2, 0, 1 };
heapSort(data);
System.out.println(Arrays.toString(data));
}
}
java实现堆排序
最新推荐文章于 2024-02-18 17:31:59 发布