Dec 26, 2008

you are given an array of integers containing only 0s and 1s. you have to place all the 0s in even position and 1s in odd position and if suppose no.

you are given an array of integers containing only 0s and 1s. you have to place all the 0s in even position and 1s in odd position and if suppose no. of 0s exceed no. of 1s or vice versa then keep them untouched. Do that in ONE PASS and WITHOUT taking EXTRA MEMORY.
input array:
{0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 }
output array:
{0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 }

idea: p0 point a[0] (even), p1 point to a[1] (odd)
if(*p0==0&&*p1==1) {p0=p0+2;p1=p1+2;}
else if(*p0==1&&*p1==0) {swap(*p0,*p1),p0=p0+2;p1p1+2;}
else if(*p0==1&&*p1==1) p1=p1+2;
else if(*p0==0&&*p1==0) p0=p0+2;

No comments:

Post a Comment