HeapSort
class Solution{
public static void main(String[] args) {
int[] nums = new int[]{4,6,8,5,9};
heapSort(nums2);
for(int i:nums2) System.out.print(i+" ");
}
/**
[4,6,8,5,9] -n/2-1-> [4,9,8,5,6] --> [9,4,8,5,6] -swap-> [6,4,8,5,9] ([6,4,8,5][9])
[6,4,8,5] --> [6,5,8,4] --> [8,5,6,4] -swap-> [4,5,6,8] ([4,5,6][8][9])
[4,5,6] --> [6,5,4] -swap->[4,5,6] ([4,5][6][8][9])
[4,5] --> [5,4] -swap-> [4,5] ([4][5][6][8][9])
*/
public static void heapSort(int[] nums){
int n = nums.length;
for(int i = n/2-1;i>=0;i--){
adjustHeap(nums,i,n);
}
/**
调整堆结构 + 交换堆顶与堆首的元素
*/
for(int j = n - 1;j>0;j--){
// 交换 因为此时
swap(nums,0,j);
// 重新对堆进行调整
adjustHeap(nums,0,j);
}
}
public static void adjustHeap(int[] nums,int index,int len){
int t = nums[index];
for(int i = 2*index+1;i<len;i=2*i+1){
if(i+1 < len && nums[i+1] > nums[i]){
i++;
}
if(nums[i] > t){
nums[index] = nums[i];
index = i;
}else{
break;
}
}
nums[index] = t;;
}
public static void swap(int[] nums ,int i,int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
Saying Less Doing More