堆排序:
建堆:
从nums.length/2-1的元素开始向前遍历,调整每个元素作为堆顶元素的堆
调整堆:
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;
}
}