-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortcolors.java
More file actions
40 lines (34 loc) · 881 Bytes
/
Copy pathSortcolors.java
File metadata and controls
40 lines (34 loc) · 881 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
public class Sortcolors {
public static void sortColors(int[] nums) {
int n = nums.length;
int i = 0;
int j = 0;
int k = n - 1;
while (j <= k) {
if (nums[j] == 1) {
j++;
} else if (nums[j] == 2) {
swap(nums, j, k);
k--;
} else {
swap(nums, j, i);
i++;
j++;
}
}
}
private static void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
public static void main(String[] args) {
int nums[] ={2,0,2,1,1,0};
sortColors(nums);
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]);
}
}
}
// time complexity - O(n)
// space complexity - O(1)