Skip to content

Commit 3d69f85

Browse files
committed
feat: added code for Dutch national flag algorithm in java
1 parent 387670d commit 3d69f85

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
public class DutchFlag {
2+
3+
public static void sortColors(int[] nums) {
4+
int low = 0, mid = 0, high = nums.length - 1;
5+
6+
while (mid <= high) {
7+
switch (nums[mid]) {
8+
case 0:
9+
// swap nums[low] and nums[mid]
10+
int temp0 = nums[low];
11+
nums[low] = nums[mid];
12+
nums[mid] = temp0;
13+
low++;
14+
mid++;
15+
break;
16+
17+
case 1:
18+
mid++;
19+
break;
20+
21+
case 2:
22+
// swap nums[mid] and nums[high]
23+
int temp2 = nums[mid];
24+
nums[mid] = nums[high];
25+
nums[high] = temp2;
26+
high--;
27+
break;
28+
}
29+
}
30+
}
31+
32+
public static void main(String[] args) {
33+
int[] nums = {2, 0, 2, 1, 1, 0};
34+
sortColors(nums);
35+
36+
System.out.print("Sorted array: ");
37+
for (int num : nums) {
38+
System.out.print(num + " ");
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)