Wednesday, December 23, 2009

for programming interviews part-2

3.wap for sorting ones and 0 in most efficient way while preserving the order.

ans:the solution as many would have guessed has to be in O(n).and the usual 2 pointer approach is correct.but ek problem the order is not preserved hence we have to think of a different approach.we can use 2 ptr approach.a slight change.in the regular approach there is one ptr in front and 2nd ptr at the end of array.
but in my approach we can have 2 ptrs such that both are at front.

#include
using namespace std;
int main()
{
int arry[5]={1,1,1,0,1};
int i=0,j=0,k=0;
for(;k<5;++k)
{
if((i==j)&&(arry[i]!=0))
{
++i;
++j;
}

else if(i==j){
j++;
}
else if(arry[j]==0){
j++;
}
else if((arry[i] == 0) && (arry[j]!=0))
{
int tmp;
tmp = arry[j];
arry[j]=arry[i];
arry[i]=tmp;
i++;
j++;
}

}
for(i=4;i>=0;--i)
cout<cin.sync();
cin.get();
return 0;
}
u can use this approach to sort(separate) the given set of non 0 number and 0 .by putting 0 at end and prserving order.

4.shuffle a deck of cards.


int array[52];
for(i=0;i<52;++i)
{
int rand=rand()%52;
swap(a[i],a[rand]);
}



No comments:

Post a Comment