Skip to content

Commit 02f6f11

Browse files
committed
added dutch national flag algorithm or dijkstra 3way partioning in sorts
1 parent 506b6d1 commit 02f6f11

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.sorts;
2+
public class DijkstraThreeWayPartition {
3+
4+
public static void threeWayPartition(int[] arr, int pivot) {
5+
int low = 0, mid = 0;
6+
int high = arr.length - 1;
7+
//this will sort the array in o(n) time complexity
8+
//also with no extra space i,e o(1) space complexity
9+
while (mid <= high) {
10+
if (arr[mid] < pivot) {
11+
// Swap
12+
int temp = arr[low];
13+
arr[low] = arr[mid];
14+
arr[mid] = temp;
15+
16+
low++;
17+
mid++;
18+
} else if (arr[mid] > pivot) {
19+
// Swap
20+
int temp = arr[mid];
21+
arr[mid] = arr[high];
22+
arr[high] = temp;
23+
24+
high--;
25+
} else {
26+
mid++;
27+
}
28+
}
29+
}
30+
31+
public static void main(String[] args) {
32+
int[] arr = {2, 1, 2, 3, 2, 1, 3, 2};
33+
int pivot = 2;
34+
threeWayPartition(arr, pivot);
35+
for (int num : arr) {
36+
System.out.print(num + " ");
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)