class Solution {
public int[] sortArray(int[] nums) {
quicksort(0, nums.length - 1, nums);
return nums;
}
private void quicksort(int left, int right, int[] nums){
if(left >= right) return;
int j = left;
int target = nums[left];
for(int i = left + 1; i <= right; i++){
if(nums[i] < target){
j++;
swap(i, j, nums);
}
}
swap(left, j, nums);
quicksort(left, j-1,nums);
quicksort(j + 1, right, nums);
}
private void swap(int i, int j, int[] nums){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
可能存在特殊用例,所以partition点可以随机选取
class Solution {
Random random = new Random();
public int[] sortArray(int[] nums) {
quicksort(0, nums.length - 1, nums);
return nums;
}
private void quicksort(int left, int right, int[] nums){
if(left >= right) return;
int idx = left + 1 + random.nextInt(right - left);
swap(idx, left, nums);
int j = left;
int target = nums[left];
for(int i = left + 1; i <= right; i++){
if(nums[i] < target){
j++;
swap(i, j, nums);
}
}
swap(left, j, nums);
quicksort(left, j-1,nums);
quicksort(j + 1, right, nums);
}
private void swap(int i, int j, int[] nums){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}