package com.heu.wsq.basic.sort_algorithm;
import java.util.Arrays;
/**
* 堆排序
* @author wsq
* @date 2021/5/27
*/
public class HeapSort {
/**
* 堆排序的思想主要有下面两步:
* 1. 将无需数组构建成堆的状态(从小到大(大顶堆),从大到小(小顶堆))
* 2. 将堆顶与数组末尾元素交换,然后下沉调整堆顶,重新构建堆状态
* 循环步骤二,完成堆排序,堆排序比较稳定
* 最差和最优时间复杂度为o(nlogn)
* 空间复杂度:o(1)(原地排序)
* @param arr
*/
public static void heapSort(int[] arr){
// 1. 将无序数组构建成最大堆
for(int i = (arr.length / 2); i >= 0; i--){
// 从第一个非叶子节点 从下到上,从右到左调整结构
downAdjust(i, arr.length, arr);
}
// 2. 循环交换集合尾部元素到堆顶,并调节堆产生的新堆顶
for(int i = arr.length - 1; i > 0; i--){
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
// 下沉调整最大堆
downAdjust(0, i, arr);
}
}
private static void downAdjust(int parentIndex, int length, int[] arr) {
if(length == 0 || parentIndex < 0){
return;
}
int temp = arr[parentIndex];
int childIndex = 2 * parentIndex + 1;
while(childIndex < length){
int rightChild = childIndex + 1;
if(rightChild < length && arr[rightChild] > arr[childIndex]){
childIndex += 1;
}
if(temp >= arr[childIndex]){
break;
}
arr[parentIndex] = arr[childIndex];
parentIndex = childIndex;
childIndex = 2* parentIndex + 1;
}
arr[parentIndex] = temp;
}
public static void main(String[] args) {
int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
}
堆排序(大顶堆、小顶堆)
最新推荐文章于 2024-05-24 13:57:20 发布