public static void heapSort(int[] nums){
if(nums == null || nums.length < 2) return;
//构建大顶堆,对于有左子树的节点有2i+1 <= n-1,反解出最大的i<=n/2-1
for(int i = nums.length / 2 - 1; i >= 0; i --){
toMaxHeap(nums, nums.length, i);
}
//交换堆顶和末端元素
for(int i = nums.length - 1; i > 0; i --){
//交换
swap(nums, i, 0);
//从堆顶开始调整结构,范围为除已交换到末端的酸雨
toMaxHeap(nums, i, 0);
}
}
private static void toMaxHeap(int[] nums, int length, int index) {
int left = index * 2 + 1;//左子树
int right = index * 2 + 2;//右子树
int maxIndex = index;
if(left < length && nums[left] > nums[maxIndex]){
maxIndex = left;
}
if(right < length && nums[right] > nums[maxIndex]){
maxIndex = right;
}
//调整结构
if(maxIndex != index){
//交换
swap(nums, index, maxIndex);
//调整子树
toMaxHeap(nums, length, maxIndex);
}
}
public static void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
java实现堆排序
于 2022-02-19 20:12:20 首次发布