array contains zeros and ones as elements.we need to bring
zeros one side and one other side in single parse.
ex:a[]={0,0,1,0,1,1,0,0}
o/p={0,0,0,0,0,1,1,1}
Answer Posted / alex r.
Single parse, n/2 steps.
Swapping without 3rd tmp variable.
#include <stdio.h>
int main(void)
{
int i,j;
int stepscount = 0;
int length = 10;
int a[10] = {1,0,0,0,1,0,0,1};
for (i=0,j=length-1;i<j;stepscount++)
{
// dont need move 0 from the start
if (a[i] == 0) i++;
// dont need move 1 from the end
if (a[j] == 1) j--;
// swap 0 and 1
if (a[i] > a[j]) {
a[i] = a[i] ^ a[j];
a[j] = a[j] ^ a[i];
a[i] = a[i] ^ a[j];
i++;
j--;
}
}
for (i = 0; i < length; i++)
{
printf("%d",a[i]);
}
printf("\nSteps: %d\n", stepscount);
return 0;
}
| Is This Answer Correct ? | 4 Yes | 1 No |
Post New Answer View All Answers
What is substring in c?
How can I make it pause before closing the program output window?
write a program to display all prime numbers
Explain the Difference between the New and Malloc keyword.
What is getch () for?
What is the best way to store flag values in a program?
How can I ensure that integer arithmetic doesnt overflow?
Why static variable is used in c?
Do you know the purpose of 'register' keyword?
Do you have any idea how to compare array with pointer in c?
How many levels of pointers have?
What is meant by realloc()?
Does c have an equivalent to pascals with statement?
What is a struct c#?
What is the purpose of void pointer?