-
Notifications
You must be signed in to change notification settings - Fork 1k
/
DutchFlag.java
53 lines (49 loc) · 1.31 KB
/
DutchFlag.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
52
53
import java.util.*;
public class DutchFlag {
private static void dutchNationalFlag(int[] array, int size){
int start = 0 , mid = 0;
int end = size-1;
while(mid < end){
switch(array[mid]){
case 0:
swap(array,start,mid);
start++;
mid++;
break;
case 1:
mid++;
break;
case 2:
swap(array,mid,end);
end--;
break;
}
}
}
private static void swap(int[] array, int i, int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] array = new int[size];
//Input Array:
for(int i = 0; i < size; i++){
array[i] = sc.nextInt();
}
dutchNationalFlag(array,size);
//Output
System.out.println("Sorted Array : ");
for(int i = 0; i < size; i++){
System.out.print(array[i]+" ");
}
}
}
//Sample output :
// 8 ->size
// 0 1 2 2 1 1 0 0 -> input array
//Output : s
// Sorted Array :
// 0 0 0 1 1 1 2 2