publicvoidquicksort(int[] nums, int l, int r){ if (l < r) { int pos = partition(nums, l, r); quicksort(nums, l, pos - 1); quicksort(nums, pos + 1, r); } }
publicintpartition(int[] nums, int l, int r){ int pivot = nums[r]; int i = l - 1; for (int j = l; j <= r; ++j) { if (nums[j] <= pivot) { i = i + 1; swap(nums, i, j); } } return i; }
privatevoidswap(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
publicint[] sortArray(int[] nums) { int len = nums.length; heapify(nums);//建堆 for (int i = len - 1; i >= 1; ) { swap(nums, 0, i); i--; siftDown(nums, 0, i); } return nums; } privatevoidheapify(int[] nums){ int len = nums.length; for (int i = (len - 1) / 2; i >= 0; i--) { siftDown(nums, i, len - 1); } }
privatevoidsiftDown(int[] nums, int k, int end){ while (2 * k + 1 <= end) { int j = 2 * k + 1; if (j + 1 <= end && nums[j + 1] > nums[j]) { j++; } if (nums[j] > nums[k]) { swap(nums, j, k); } else { break; } k = j; } }
privatevoidswap(int[] nums, int index1, int index2){ int temp = nums[index1]; nums[index1] = nums[index2]; nums[index2] = temp; } }