Skip to content

Commit 4a83576

Browse files
Add DNF sort (TheAlgorithms#2400)
1 parent f6f12c0 commit 4a83576

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Sorts/DNFSort.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package Sorts;
2+
3+
public class DNFSort {
4+
// Sort the input array, the array is assumed to
5+
// have values in {0, 1, 2}
6+
static void sort012(int a[], int arr_size) {
7+
int low = 0;
8+
int high = arr_size - 1;
9+
int mid = 0, temp = 0;
10+
while (mid <= high) {
11+
switch (a[mid]) {
12+
case 0: {
13+
temp = a[low];
14+
a[low] = a[mid];
15+
a[mid] = temp;
16+
low++;
17+
mid++;
18+
break;
19+
}
20+
case 1:
21+
mid++;
22+
break;
23+
case 2: {
24+
temp = a[mid];
25+
a[mid] = a[high];
26+
a[high] = temp;
27+
high--;
28+
break;
29+
}
30+
}
31+
}
32+
}
33+
34+
/* Utility function to print array arr[] */
35+
static void printArray(int arr[], int arr_size) {
36+
for (int i = 0; i < arr_size; i++)
37+
System.out.print(arr[i] + " ");
38+
System.out.println("");
39+
}
40+
41+
/*Driver function to check for above functions*/
42+
public static void main(String[] args) {
43+
int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
44+
int arr_size = arr.length;
45+
sort012(arr, arr_size);
46+
System.out.println("Array after seggregation ");
47+
printArray(arr, arr_size);
48+
}
49+
}

0 commit comments

Comments
 (0)