I’ve come up with the following program to do it, but it does not seem to work and goes into infinite loop. Its working is similar to quicksort.
int main()
{
int arr[] = {1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1};
int N = 18;
int *front, *last;
front = arr;
last = arr + N;
while(front <= last)
{
while( (front < last) && (*front == 0) )
front++;
while( (front < last) && (*last == 1) )
last--;
if( front < last)
{
int temp = *front;
*front = *last;
*last = temp;
front ++;
last--;
}
}
for(int i=0;i<N;i++)
printf("%d ",arr[i]);
return 0;
}
I see at least two problems in the program:
Problem 1:
is incorrect. It should be:
because
Problem2:
Next your while loop:
is incorrect and should be:
In your case when front and last become equal, your loop continues but
neither front nor last get modified at this point, resulting in infinite loop.
When front and last become equal, it makes no point to continue, your array
would have been sorted by then.