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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| class Solution {
public int[] sortArray(int[] nums) { quickSort(nums); return nums; }
private void quickSort(int[] arr) { quickSort(arr, 0, arr.length - 1); }
private void quickSort(int[] arr, int start, int end) { if (start == end || start == end + 1) { return; }
int middle = partition(arr, start, end);
quickSort(arr, start, middle - 1); quickSort(arr, middle + 1, end); }
private int partition(int[] arr, int start, int end) { Random rand = new Random(); int middle = rand.nextInt((end - start) + 1) + start;
swap(arr, middle, start); int privot = arr[start];
int left = start + 1; int right = end;
while (left < right) { while (left < right && arr[left] <= privot) left++; while (left < right && arr[right] >= privot) right--; if (left < right) { swap(arr, left, right); left++; right--; } }
if (left == right && arr[right] > privot) right--; swap(arr, start, right); return right; }
private void swap(int[] arr, int i, int j) { if (i == j) return; arr[i] = arr[i] ^ arr[j]; arr[j] = arr[j] ^ arr[i]; arr[i] = arr[i] ^ arr[j]; } }
|