- 思路
- 算法属性
- 代码
思路
参考文章及其动图展示快排链接:【点我】
(堆是一棵顺序存储的完全二叉树。其中每个结点的关键字都不大于其孩子结点的关键字,这样的堆称为小根堆。其中每个结点的关键字都不小于其孩子结点的关键字,这样的堆称为大根堆。)
- 根据初始数组去构造初始大根堆(构建一个完全二叉树,保证所有的父结点都比它的孩子结点数值大)。(循环n/2次,因为最后一个非叶子结点是第 ⌊n/2⌋ 个)
- 每次交换第一个和最后一个元素(第一个数是大根堆里最大的数,交换后最大值就放在了最后边),然后把剩下(n-1个)元素重新调整为大根堆。
- 重复第二步
算法属性
排序类型 | 时间复杂度(平均) | 时间复杂度(最坏) | 时间复杂度(最好) | 空间复杂度 | 稳定性 | 复杂性 |
交换排序 | O(NlogN) | O(NlogN) | O(NlogN) | O(1) | 不稳定 | 较复杂 |
代码
public static int[] headSort(int[] inputList) {
int length = inputList.length;
for (int i = length / 2; i >= 0; i--) {// 建立初始堆
heapAdjust(inputList, i, length);
}
for (int i = length - 1; i >= 0; i--) {// n-1次循环完成排列
// 将最后一个元素和第一个元素进行交换(第一个元素是最大的,交换位置后,最大的就在排最后了)
int tem = inputList[i];
inputList[i] = inputList[0];
inputList[0] = tem;
heapAdjust(inputList, 0, i);// 将inputList中前i个记录重新调整为大顶堆
}
return inputList;
}
/**
* 将数组构造成大根堆
* @param inputList
* 数组
* @param parent
* 数组父节点
* @param length
* 数组的长度
*/
public static void heapAdjust(int[] inputList, int parent, int length) {// 构建大顶堆
int tem = inputList[parent];// tem保存当前父节点
int child = 2 * parent + 1;// 先获得左孩子
while (child < length) {
// 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点
if (child + 1 < length && inputList[child + 1] > inputList[child]) {
child++;
}
if (tem >= inputList[child]) {// 如果当前父节点是最大的,break
break;
}
inputList[parent] = inputList[child];// 将两个孩子中的最大值付给父亲
parent = child; // 将当前子节点作为父节点
child = 2 * parent + 1; // 选取孩子结点的左孩子结点,继续向下筛选
}
inputList[parent] = tem;
}