Tuesday, March 22, 2011

we have an array of 2n elements like "a1 a2...an b1 b2...bn". WAP to rearrange the array as "a1 b1 a2 b2...an bn" time complexity is O(n) no extra RAM

#include
#define SWAP(a,b) a^=b^=a^=b

int string[100];
int m;

void Replace(int n,int start){
int i,j;
for(i=start,j=0;j {
SWAP(string[i],string[n+i]);
}
n=n-1;
if(n>0)
Replace(n,start+1);
}

main()
{
int i;
printf("Enter no of elements (max 100): ");
scanf("%d",&m);
if(m%2){
printf("odd nos\n");
}
else{
printf("Enter numbers: ");
for(i=0;i scanf("%d",&string[i]);
for(i=0;i printf("%d\t",string[i]);
printf("\n");

Replace(m/2-1,1);
for(i=0;i printf("%d\t",string[i]);
printf("\n");
}
}

No comments :