Skip to content

Commit d90b703

Browse files
committed
Added and edited Dtch_national_flag
1 parent 16a6c5b commit d90b703

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Dutch_national_flag2.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*The problem was posed with three colours, here `0′, `1′ and `2′. The array is divided into four sections:
2+
a[1..Lo-1] zeroes (red)
3+
a[Lo..Mid-1] ones (white)
4+
a[Mid..Hi] unknown
5+
a[Hi+1..N] twos (blue)
6+
If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.
7+
Similarly, if the element is 1 then keep it as it is but shrink the unknown range.
8+
If the element is 2 then swap it with an element in high range. */
9+
import java.io.*;
10+
11+
class countzot {
12+
13+
// Sort the input array, the array is assumed to
14+
// have values in {0, 1, 2}
15+
static void sort012(int a[], int arr_size)
16+
{
17+
int lo = 0;
18+
int hi = arr_size - 1;
19+
int mid = 0, temp = 0;
20+
while (mid <= hi) {
21+
switch (a[mid]) {
22+
case 0: {
23+
temp = a[lo];
24+
a[lo] = a[mid];
25+
a[mid] = temp;
26+
lo++;
27+
mid++;
28+
break;
29+
}
30+
case 1:
31+
mid++;
32+
break;
33+
case 2: {
34+
temp = a[mid];
35+
a[mid] = a[hi];
36+
a[hi] = temp;
37+
hi--;
38+
break;
39+
}
40+
}
41+
}
42+
}
43+
44+
/* Utility function to print array arr[] */
45+
static void printArray(int arr[], int arr_size)
46+
{
47+
int i;
48+
for (i = 0; i < arr_size; i++)
49+
System.out.print(arr[i] + " ");
50+
System.out.println("");
51+
}
52+
53+
/*Driver function to check for above functions*/
54+
public static void main(String[] args)
55+
{
56+
int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
57+
int arr_size = arr.length;
58+
sort012(arr, arr_size);
59+
System.out.println("Array after seggregation ");
60+
printArray(arr, arr_size);
61+
}
62+
}

0 commit comments

Comments
 (0)