@Gene
your code's last 3 line gives doubt.
.......
for (i = j = 0; j < M; j++)
while (c[j]--)
a[i++] = j;
.......
Is it don't make the complexity more than O(n) ??
Same logic i implemented ....used continue statement to do the
modification in the array in 1 loop itself.
#include<stdio.h>
void sort012(int array[],int size)
{
int no[3]={0,0,0},i;
for(i=0;i<size;i++)
{
no[array[i]]++;
}
for(i=0;i<size++;i++)
{
if(no[0]!=0)
{
array[i]=0;
no[0]--;
continue;
}
else if(no[1]!=0)
{
array[i]=1;
no[1]--;
continue;
}
else if(no[2]!=0)
{
array[i]=2;
no[2]--;
continue;
}
}
}
int main()
{
int array[]={1,1,2,0,2,1,0,2,1};
int i,size=sizeof(array)/sizeof(array[0]);
sort012(array,size);
for(i=0;i<size;i++)
printf("%d ",array[i]);
}
On 6/30/10, Gene <[email protected]> wrote:
> On Jun 29, 3:26 pm, sharad kumar <[email protected]> wrote:
>> how to sort an array containing 0's 1's and 2's in O(n)time and sorting
>> technique must be inplace
>
> #define M 3
>
> void sort(int *a, int n)
> {
> int i, j, c[M];
> for (j = 0; j < M; j++) c[j] = 0;
> for (i = 0; i < n; i++) ++c[a[i]];
> for (i = j = 0; j < M; j++)
> while (c[j]--)
> a[i++] = j;
> }
>
> --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>
>
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.