Skip to content

Commit 9cfe9d0

Browse files
authored
Create SortColors.java
1 parent 3ae2b9b commit 9cfe9d0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

SortColors.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
/*
3+
A rather straight forward solution is a two-pass algorithm using counting sort.
4+
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array
5+
with total number of 0's, then 1's and followed by 2's.
6+
7+
*/
8+
public void sortColors(int[] nums) {
9+
10+
11+
// pointer soln
12+
int i=0,nextZero=0,nextTwo=nums.length-1;
13+
while(i<=nextTwo){
14+
// if zero tthen swap i with nextzero
15+
if(nums[i]==0){
16+
int temp=nums[i];
17+
nums[i]=nums[nextZero];
18+
nums[nextZero]=temp;
19+
i++;
20+
nextZero++;
21+
}
22+
// if zero tthen swap i with nextTwo
23+
else if(nums[i]==2){
24+
int temp=nums[i];
25+
nums[i]=nums[nextTwo];
26+
nums[nextTwo]=temp;
27+
//i++; // here is the biggest mistake
28+
nextTwo--;
29+
}
30+
//if one then just increase i don't do anything
31+
else {
32+
i++;
33+
}
34+
35+
36+
}
37+
38+
}
39+
}

0 commit comments

Comments
 (0)