top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Rearrange even and odd numbers

+2 votes
412 views

If you have an array with random odd and even numbers, what is the most efficient way to put all even numbers on one side and all odd numbers on the other side of the array?

posted Nov 30, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

The solution is in-place quick sort type..

#include <iostream>
using namespace std;

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9,10};
    int n = 10;
    int i=0, j = n-1, tmp;
    while(i <= j)
    {
        while(a[i]%2 == 0)
        {
            i++;
            if(i == j) break;
        }
        if(i == j) break;
        while(a[j]%2 != 0)
        {
            j--;
            if(i == j) break;
        }
        if(i == j) break;
        tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
        i++;
        j--;
    }
    for(int i=0; i<n; i++) cout << a[i] << " ";
    cout << endl;
    return 0;
}

Order : O(N)

answer Dec 3, 2013 by Raghu
0 votes

Complexity o(n^2)

void sortarrayinorder(int arr[],int size)
{
     int i,j,tem,k;
     for(i=1;i<size;i++)
     {
       for(j=0;j<i;j++)
       {
         if((arr[j]%2)!=0 && (arr[i]%2)==0)
         {
           tem=arr[j];
           arr[j]=arr[i];
           for(k =i;k>j;k--)
             arr[k]=arr[k-1];

           arr[k+1]=tem;
         }
      }
   }     
}
answer Dec 1, 2013 by Salil Agrawal
Similar Questions
+3 votes
               40

       30              60

   25      35      50      70

 12  27  32

Answer = -59

+3 votes

A list contains a set of numbers, one number presents once and other numbers present even no. of times. Find out the number that occurs once in the list.

+2 votes

Given an infinite supply of coins of denominations {20,10,5,1}, find out total number of way to make change of given amount - 'n'?
For example, if given amount is 20, there are 10 ways to make this change as shown below -
(1 of 20),(1 of 10 + 2 of 5),(1 of 10 + 1 of 5 + 5 of 1),(1 of 10 + 10 of 1), (2 of 10), (1 of 5 + 15 of 1),(2 of 5 + 10 of 1),(3 of 5 + 5 of 1),(4 of 5),(20 of 1)

If the amount given is 0 then the total number of ways to make change is 1 - using 0 coins of every given denomination.

+5 votes

Input: {5, 8, 5, 3, 3, 2, 7}
Output: {5, 8, 3, 2, 7, ?, ?}

Idea is that we should remove the duplicate number from the array and should return the array in the original form (obviously without duplicate).

Please help me with an efficient algorithm or C code.

...