-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
47 lines (42 loc) · 1.24 KB
/
Solution.java
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
package L912;
import java.util.Random;
public class Solution {
public int[] sortArray(int[] nums) {
if (nums == null || nums.length < 2) return nums;
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] arr, int l, int r) {
if (l >= r) return;
int mid = partition(arr, l, r);
quickSort(arr, l, mid);
quickSort(arr, mid + 1, r);
}
private int partition(int[] arr, int l, int r) {
if (l > r) return -1;
if (l == r) return l;
int mid = l + (int) Math.random() % (r - l + 1);
int midVal = arr[mid];
while (l <= r) {
while (arr[l] < midVal)l++;
while (arr[r] > midVal)r--;
if (l == r)break;
if (l < r) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
return r;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {5, 1, 1, 2, 0, 0};
int[] ans = solution.sortArray(nums);
for (int i = 0; i < ans.length; ++i) {
System.out.print(ans[i] + " ");
}
}
}