Tuesday 2 October 2012

Re-arrange the odd/even to odd/even places





#include<stdio.h>

void Swap (int A[], int i, int j)
{
    int temp = A[i];
    A[i]=A[j];
    A[j]=temp;
}

int main()
{
    int A[] = {3,1,4,5,7,6,10,8};
    int i=0,j=1,n;
    n=sizeof(A)/sizeof(int);
    while(i<n)
    {
        while(i<n && A[i]%2 == 0)
            i+=2;
        while(j<n && A[j]%2 == 1)
            j+=2;
        if(i<n && j<n)
            Swap(A,i,j);
    }// end of while

    for(i=0;i<n;i++)
        printf(" %d",A[i]);

return 0;
}

Let me know your thoughts

2 comments:

  1. Good answer, but won't this fail if j is greater than n and i is less than n while A[i]%2 is not equal to zero?

    For example:

    int A[] = {3,4,5,7,2}

    First Loop:
    i = 0
    j = 1
    swap()
    A[] = {4,3,5,7,2}

    Second Loop:
    i = 0 + 2
    j = 1 + 2 + 2
    No swap because j is not less than n!

    Third Loop:
    No change in i or j

    Infinite Loop

    Change while(i<n) to while(i<n && i<j) for the first for loop and you will eliminate your infinite loop.

    ReplyDelete
  2. @Ryan,

    Thanks for your point, but for now i am only equal number of even and odd Integers.

    ReplyDelete