File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ package Misc ;
2
+ import java .util .*;
3
+ /**
4
+ The array is divided into four sections:
5
+ a[1..Lo-1] zeroes
6
+ a[Lo..Mid-1] ones
7
+ a[Mid..Hi] unknown
8
+ a[Hi+1..N] twos
9
+ If array [mid] =0, then swap array [mid] with array [low] and increment both pointers once.
10
+ If array [mid] = 1, then no swapping is required. Increment mid pointer once.
11
+ If array [mid] = 2, then we swap array [mid] with array [high] and decrement the high pointer once.
12
+ For more information on the Dutch national flag algorithm refer https://en.wikipedia.org/wiki/Dutch_national_flag_problem
13
+ */
14
+ public class Sort012D {
15
+ public static void main (String args []) {
16
+ Scanner np = new Scanner (System .in );
17
+ int n = np .nextInt ();
18
+ int a [] = new int [n ];
19
+ for (int i = 0 ; i < n ; i ++) {
20
+ a [i ] = np .nextInt ();
21
+ }
22
+ sort012 (a );}
23
+
24
+ public static void sort012 (int []a ){
25
+ int l = 0 ;
26
+ int h = a .length - 1 ;
27
+ int mid = 0 ;
28
+ int temp ;
29
+ while (mid <= h ) {
30
+ switch (a [mid ]) {
31
+ case 0 : {
32
+ temp = a [l ];
33
+ a [l ] = a [mid ];
34
+ a [mid ] = temp ;
35
+ l ++;
36
+ mid ++;
37
+ break ;}
38
+ case 1 :
39
+ mid ++;
40
+ break ;
41
+ case 2 : {
42
+ temp = a [mid ];
43
+ a [mid ] = a [h ];
44
+ a [h ] = temp ;
45
+ h --;
46
+ break ;
47
+ }
48
+ }
49
+ }
50
+ System .out .println ("the Sorted array is " );
51
+ for (int i = 0 ; i < a .length ; i ++)
52
+ System .out .print (+a [i ] + " " ); }
53
+ }
You can’t perform that action at this time.
0 commit comments