-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathSortColors.java
More file actions
45 lines (34 loc) · 711 Bytes
/
Copy pathSortColors.java
File metadata and controls
45 lines (34 loc) · 711 Bytes
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
package leetcode.medium;
/**
* Created by nikoo28 on 12/19/17 1:12 AM
*/
class SortColors {
void sortColors(int[] nums) {
int start = 0;
int mid = 0;
int end = nums.length - 1;
while (mid <= end) {
switch (nums[mid]) {
case 0:
// Swap with start index
swap(nums, start, mid);
mid++;
start++;
break;
case 1:
mid++;
break;
case 2:
// Swap with end index
swap(nums, mid, end);
end--;
break;
}
}
}
private void swap(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}