1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public int[] sortArray(int[] nums) {
qsort(nums, 0, nums.length - 1); return nums; }
private void qsort(int[] nums, int lo, int hi) { if (lo >= hi) { return; }
int rand = ThreadLocalRandom.current().nextInt(lo, hi); swap(nums, lo, rand);
int i = lo; int j = hi; int pivot = nums[lo];
while (i < j) { while (i < j && nums[j] >= pivot) j--; while (i < j && nums[i] <= pivot) i++;
swap(nums, i, j); }
swap(nums, lo, i); qsort(nums, lo, i - 1); qsort(nums, i + 1, hi); }
private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
|