Skip to content

Instantly share code, notes, and snippets.

@anil477
Created April 14, 2017 06:15
Show Gist options
  • Save anil477/3e3f629f9b5bb80e8c21bced31af7576 to your computer and use it in GitHub Desktop.
Save anil477/3e3f629f9b5bb80e8c21bced31af7576 to your computer and use it in GitHub Desktop.
Sort an array of 0,1 and 2. Dutch National Flag Problem
// Java program to sort an array of 0, 1 and 2
import java.io.*;
class countzot {
// Sort the input array, the array is assumed to
// have values in {0, 1, 2}
static void sort012(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0,temp=0;
while (mid <= hi)
{
switch (a[mid])
{
case 0:
{
if( a[lo] != a[mid]) {
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
}
lo++;
mid++;
break;
}
case 1:
mid++;
break;
case 2:
{
if( a[mid] != a[hi]) {
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
}
hi--;
break;
}
}
}
System.out.println("middle " + mid);
System.out.println("high " + hi);
System.out.println("low " + lo);
}
/* Utility function to print array arr[] */
static void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
System.out.print(arr[i]+" ");
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 1, 2, 0, 1, 2};
int arr_size = arr.length;
sort012(arr, arr_size);
System.out.println("Array after seggregation ");
printArray(arr, arr_size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment