Home > Uncategorized > A game with array

A game with array

Hi … I know that its been too long since I had last posted into my blog and the main reason for that was a lack of interesting topic to discuss on my page. But last day I happen to meet a person(named Rajesh) who coined a simple question of re-ordering numbers in an array.

The situation is like this: we have an array of integers which contains randomly ordered numbers. We would wanna move all odd numbers to the beginning of the array and the even numbers to the end – still the ordering doesn’t matter. Below is the code that I believe would do the job in the least number of iterations:

int arr[]={1,2,3,4,5,6,7,8,9,10};

swap(int *p, int *q)
{

*p = *p ^ *q;
*q = *p ^ *q;
*p = *p ^ *q;

}

int checkeven(int value)
{

return !(value & 0x1);

}

int checkodd(int value)
{

return (value & 0x1);

}

int *find(int *start, int *end, int step, int (*cond)(int) )
{

while(((step > 0) && (start <= end)) || ((step < 0) && (end <= start)))
{

if(cond(*start))

break;

start += step;

}

return start;

}

reorder(int *start, int size)
{

int *end = start + size - 1;

while(1)
{

// find an even no. starting from the front
start = find(start, end, 1, checkeven);

//find an odd no. starting from the back
end = find(end, start, -1, checkodd);

if(start >= end)

break;

swap(start, end);

}

}

main()
{

reorder(arr, sizeof(arr)/sizeof(arr[0]));

}

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.