堆排序
根据阿顾同学的《堆排序算法(图解详细流程)》修改的,详细算法可以链接查看,有问题可以指出,谢谢~
Java实现代码
public class Sort {
public static void main(String[] args) {
int[] array = {9, 8, 7, 6, 11, 4, 13, 11,3, 2, 1, 0, -1, -2, -3};
// test 堆排序
heapSort(array);
System.out.println(Arrays.toString(array));
}
// 堆排序
public static void heapSort(int[] array){
// 创建一个大顶堆
heapInsert(array, array.length - 1);
int len = array.length - 1;
while(len > 0){
// len == 1是说明数组中还有两个数无序
swap(array, 0, len);
len--;
heapInsert(array, len);
}
}
// 将数组array中无序部分调整为大顶堆,len为无序数组的最大下标
public static void heapInsert(int[] array, int len){
for(int i = 0; i <= len; i++){
int curIndex = i;
int fatherIndex = (curIndex - 1) / 2;
while(array[curIndex] > array[fatherIndex]){
swap(array, curIndex, fatherIndex);
// 当交换后,需要比较新的array[curIndex]和其父节点值的大小,直至无法交换
curIndex = fatherIndex;
fatherIndex = (curIndex - 1) / 2;
}
}
}
// 交换
public static void swap(int[] array, int i, int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}