forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortColors.java
51 lines (45 loc) · 1.19 KB
/
SortColors.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
48
49
50
51
//Dutch National Flag Algorithm
public class SortColors {
//sort the arrays , have value as 0,1,2
static void sortcolor(int[] nums) {
int low = 0;
int high = nums.length - 1;
int mid = 0;
int ans = 0;
while(mid<=high){
switch(nums[mid]){
case 0: {
ans = nums[low];
nums[low] =nums[mid];
nums[mid]=ans;
low++ ; mid++;
break;
}
case 1: {
mid++;
break;
}
case 2: {
ans = nums[mid];
nums[mid]=nums[high];
nums[high]=ans;
high--;
break;
}
}
}
}
//for print the array
static void printArray(int nums[])
{
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
int[] nums = {2,0,2,1,1,0};
sortcolor(nums);
printArray(nums);
}
}