forked from Soumojitshome2023/DSA_Hacktoberfest_2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdutchFlag.java
52 lines (41 loc) · 1.41 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
import java.util.*;
public class dutchFlag {
public static void sortArray(ArrayList<Integer> arr, int n) {
int low = 0, mid = 0, high = n - 1; // 3 pointers
while (mid <= high) {
if (arr.get(mid) == 0) {
// swapping arr[low] and arr[mid]
int temp = arr.get(low);
arr.set(low, arr.get(mid));
arr.set(mid, temp);
low++;
mid++;
} else if (arr.get(mid) == 1) {
mid++;
} else {
// swapping arr[mid] and arr[high]
int temp = arr.get(mid);
arr.set(mid, arr.get(high));
arr.set(high, temp);
high--;
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in array: ");
int n= sc.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; i++) {
System.out.print("Enter element " + (i+1)+"->");
int x = sc.nextInt();
arr.add(x);
}
sortArray(arr, n);
System.out.println("After sorting:");
for (int i = 0; i < n; i++) {
System.out.print(arr.get(i) + " ");
}
System.out.println();
}
}