Skip to content

Instantly share code, notes, and snippets.

@ajaynitt
Last active August 29, 2015 14:07
Show Gist options
  • Save ajaynitt/361a65c2136a1210bf52 to your computer and use it in GitHub Desktop.
Save ajaynitt/361a65c2136a1210bf52 to your computer and use it in GitHub Desktop.
Sort an array of 0s, 1s and 2s
/*
Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s and all 2s in last.
Example
Input = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
Output = {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
soln:Dutch National Flag Algorithm, or 3-way Partitioning —
*/
void sort012(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0;
while(mid <= hi)
{
switch(a[mid])
{
case 0:
swap(&a[lo++], &a[mid++]);
break;
case 1:
mid++;
break;
case 2:
swap(&a[mid], &a[hi--]);
break;
}
}
}
@ajaynitt
Copy link
Author

The above code performs unnecessary swaps for inputs like 0 0 0 0 1 1 1 2 2 2 2 2 : lo=4 and mid=7 and hi=11. In present code: first 7 exchanged with 11 and hi become 10 and mid is still pointing to 7. again same operation is till the mid <= hi. But it is really not required. We can put following loop before switch condition to make sure that hi is pointing to location which is not 2 so that it would eliminate unnecessary swaps of 2.
while ((a[hi]==2) && hi >= mid)
–hi;
if (hi < mid)
break;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment