堆排序算法代码实现
class HeapSort {
public static void main(String[] args) {
int[] src = {1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19};
heapSort(src);
for(int num : src){
System.out.print(num + " ");
}
}
public static void heapSort(int[] nums){
buildMaxHeap(nums,nums.length);
for(int i = nums.length - 1; i >= 0; i--){
swap(nums,i,0);
buildMaxHeap(nums,i);
}
}
public static void buildMaxHeap(int[] nums,int length){
for(int i = (length - 2) / 2; i >= 0; i--){
maxHeapfy(nums,i,length - 1);
}
}
public static void maxHeapfy(int[] nums,int index,int end){
if(index >= end){
return;
}
int max = index;
int left = index * 2 + 1;
int right = index * 2 + 2;
if(left <= end && nums[left] > nums[max])
max = left;
if(right <= end && nums[right] > nums[max])
max = right;
if(max != index) {
swap(nums, index, max);
maxHeapfy(nums, max, end);
}
}
public static void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}