Sort an array of 0s, 1s and 2s |
Dutch National Flag problem
👀👀👀👀👀
/*
* This program defines a sortArray() method that sorts
* an array of 0s, 1s, and 2s using
* the Dutch National Flag algorithm.
*/
public class Sort012 {
public static void swap(int[] arr,int i,int j) {
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void sortArray(int[] arr) {
int low =0;
int mid =0;
int high =arr.length-1;
while(mid<=high) {
switch (arr[mid]) {
case 0:
swap(arr,low,mid);
low++;
mid++;
break;
case 1:
mid++;
break;
case 2:
swap(arr,mid,high);
high--;
break;
default:
break;
}
}
}
public static void main(String... aa) {
int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};
sortArray(arr);
for(int i:arr) {
System.out.print(i+" ");
}
}
}
Output:
0 0 0 0 1 1 1 1 2 2 2 2