堆排序:
- 声明全局堆长度
- 建堆(大顶堆)
- 从最后一个元素开始向前遍历,进行:1. 交换最后元素和堆顶元素;2. 全局堆长度-1;3. 调整大顶堆(从第0个位置开始)
建堆:
从nums.length/2-1的元素开始向前遍历,调整每个元素作为堆顶元素的堆
调整堆:
- 找到i的左右子节点的位置left和right
- 分别比较left和i、right和i谁更大,用largest指向
- 如果largest=i,表明已经是个大顶堆,否则,交换largest和i位置的元素,递归调整largest作为堆顶元素的堆
class Solution {static int heapLen;public int[] sortArray(int[] nums) {heapSort(nums);return nums;}public void heapSort(int[] nums) {heapLen = nums.length;buildHeap(nums);// for (int i = heapLen - 1; i > 0; --i) {for (int i = nums.length - 1; i > 0; --i){swap(nums, 0, i);--heapLen;// adjustHeap(nums, i);adjustHeap(nums, 0);}}public void buildHeap(int[] nums) {for (int i = nums.length / 2 - 1; i >= 0; --i) {adjustHeap(nums, i);}}public void adjustHeap(int[] nums, int i) {int left = 2 * i + 1;int right = 2 * i + 2;int largest = i;// if (left < heapLen && nums[left] > nums[largest]) largest = left;if (right < heapLen && nums[right] > nums[largest]) largest = right;if (left < heapLen && nums[left] > nums[largest]) largest = left;if (largest != i) {swap(nums, i, largest);adjustHeap(nums, largest);}}public void swap(int[] nums, int i, int j) {int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}
}