-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDutch_flag_algorithm.java
More file actions
46 lines (38 loc) · 1.14 KB
/
Dutch_flag_algorithm.java
File metadata and controls
46 lines (38 loc) · 1.14 KB
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
import java.util.Scanner;
public class Main {
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void sortedarr(int[] arr, int num) {
int low = 0, mid = 0, high = num - 1;
while (mid <= high) {
if (arr[mid] == 0) {
swap(arr, low, mid);
low++;
mid++;
} else if (arr[mid] == 2) {
swap(arr, mid, high);
high--;
} else {
mid++;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("number of elements:");
int len = input.nextInt();
int[] arr = new int[len];
System.out.println("elements (0, 1, or 2):");
for (int i = 0; i < len; i++) {
arr[i] = input.nextInt();
}
sortedarr(arr, len);
System.out.println("\nsorted arr");
for (int i = 0; i < len; i++) {
System.out.print(arr[i] + " ");
}
}
}