-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution75.java
39 lines (32 loc) · 937 Bytes
/
Solution75.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
package leetcode.sort;
public class Solution75 {
public static void main(String[] args) {
new Solution75().sortColors(new int[]{2, 0, 2, 1, 1, 0});
}
public void sortColors(int[] nums) {
sort(nums, 0, nums.length - 1);
}
private void sort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int base = nums[left];
int l = left, mid = left + 1, r = right;
while (mid <= r) {
if (nums[mid] < base) {
swap(nums, l++, mid++);
} else if (nums[mid] > base) {
swap(nums, mid, r--);
} else {
mid++;
}
}
sort(nums, left, l - 1);
sort(nums, mid, right);
}
private void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}