Skip to content

Instantly share code, notes, and snippets.

@XDo0
Last active October 10, 2022 08:15
Show Gist options
  • Save XDo0/04dce22e1f43c3baee5ddd4288a8b201 to your computer and use it in GitHub Desktop.
Save XDo0/04dce22e1f43c3baee5ddd4288a8b201 to your computer and use it in GitHub Desktop.
quick sort [random select pivot](https://suanfa8.com/quick-sort/random-select-pivot)
import java.util.Random;
class Solution {
private final static Random random = new Random(System.currentTimeMillis());
public int[] sortArray(int[] nums) {
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int pivotIndex = partition(nums, left, right);
quickSort(nums, left, pivotIndex - 1);
quickSort(nums, pivotIndex + 1, right);
}
private int partition(int[] nums, int left, int right) {
// [left..right]
int randomIndex = left + random.nextInt(right - left + 1);
swap(nums, left, randomIndex);
int pivot = nums[left];
// j记录pivot对应数值的最后位置+1
int j = left + 1;
// all in nums[left + 1..j) <= pivot
// all in nums[j..i) > pivot
for (int i = left + 1; i <= right; i++){
// 把小于pivot的值交换到左面,j记录下一个待交换的位置
if (nums[i] <= pivot) {
swap(nums, i, j);
j++;
}
}
swap(nums, left, j - 1);
return j - 1;
}
private void swap(int[] nums, int index1, int index2) {
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment