堆排序:
- 聲明全局堆長度
- 建堆(大頂堆)
- 從最后一個元素開始向前遍歷,進行: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;}
}