您的位置:首页 > 其它

排序-堆排序

2016-05-04 00:00 162 查看
主要思路:

(1)根据初始数组去构造 初 始 堆 (构建一个完全二叉树,保证所有的父结点都比它的孩子结点数值大)。

(2)每次交换 第一个 最后一个元素,输出最后一个元素(最大值),然后把 剩下元素 重新调整为大根堆。

public class HeapSort {

public static void main(String[] args) {
int[] array = { 2, 3, 5, 1, 4 };
heapSort(array);
}

public static void heapSort(int[] list) {
// 循环建立初始堆
for (int i = list.length / 2; i >= 0; i--) {
heapAdjust(list, i, list.length);
System.out.print("初始化(" + i + "):");
printArray(list);
}
// 进行n-1次循环,完成排序
for (int i = list.length - 1; i > 0; i--) {
// 最后一个元素和第一元素进行交换
int temp = list[i];
list[i] = list[0];
list[0] = temp;
// 调整前面元素组成的堆
heapAdjust(list, 0, i); // 0~i,忽略i后面的,相当于最大的数移到数组尾部后已经被“移除”
System.out.format("第 %d 趟:\t", list.length - i);
printArray(list);
}
}

/**
* 将array[parent,length)调整为最大堆
*/
private static void heapAdjust(int[] array, int parent, int length) {
int temp = array[parent]; // temp保存当前父节点
int child = 2 * parent + 1; // 先获得左孩子
while (child < length) {
// 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点
if (child + 1 < length && array[child] < array[child + 1]) {
child++;
}
// 如果父结点的值已经大于孩子结点的值,则直接结束
if (temp >= array[child])
break;
// 把孩子结点的值赋给父结点
array[parent] = array[child];
// 选取孩子结点的左孩子结点,继续向下筛选
parent = child;
child = 2 * child + 1;
}
array[parent] = temp;
}

private static void printArray(int[] array) {
for (int i = 0; i < array.length - 1; i++)
System.out.print(array[i] + ",");
System.out.println(array[array.length - 1]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  堆排序