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 linear search?
Why doesn't C support function overloading?
Why static is used in c?
What is the right way to use errno?
WRITE A CODE IN C TO SEARCH A FILE FROM NOTEPAD FILE.
How to establish connection with oracle database software from c language?
Devise a program that inputs a 3 digit number n and finds out whether the number is prime or not. Find out its factors.
#include main() { char s[] = "Bouquets and Brickbats"; printf(" %c, ",*(&s[2])); printf("%s, ",s+5); printf(" %s",s); printf(" %c",*(s+2)); }
Write a program to find factorial of a number using recursive function.
What is New modifiers?
Explain why c is faster than c++?
why return type of main is not necessary in linux
Why is python slower than c?
Is there a way to have non-constant case labels (i.e. Ranges or arbitrary expressions)?
In C language what is a 'dangling pointer'?