简体   繁体   中英

Rearrange even and odd in an array

I have written a program to place all even elements of the array to the left and odd ones to the right half of the array. The order of elements is not of concern. I was wondering if there is more efficient algorithm than this. My worst case complexity is O(n/2). Here is the code.

// Program to shift all even numbers in an array to left and odd to the right. Order of digits is not important.

import java.util.*;
import java.lang.*;
import java.io.*;


class Rearrange
{
public static void main (String[] args) throws java.lang.Exception
{
    // your code goes here
    int[] array = new int[] {1,2,3,4,5,6,7};

    // keep two pointers.
    int odd, even;
    odd = 0; 
    even = array.length-1;
    int i;

    // Code to re-arrange the contents of the array
    i=0;
    while(i<array.length){
        if(array[i]%2!=0){
            odd = i;
            break;
        }
        i++;    
    }

    i=array.length-1;
    while(i>=0){
        if(array[i]%2==0){
            even = i;
            break;
        }
        i--;    
    }

    while(odd<even){
        if((array[odd]%2!=0) && (array[even]%2==0)){
            // swap contents
            array[odd] = array[odd] + array[even];
            array[even] = array[odd] - array[even];
            array[odd] = array[odd] - array[even];
            odd++;
            even--;
        }

        else if(array[odd]%2==0){
            odd++;
        }

        else if(array[even]%2!=0){
            even--;
        }

        else
            continue;
    }
    for(int val : array)
        System.out.println(val+" ");

}
}

For any algorithm without sufficient information about structure of data you cannot do it in less than O(N) where N is the input size because if you do it faster that means you are not considering a part of the input hence algorithm might be incorrect.

Here is in-place code for you problem :-

int i=0,j=n-1;

while(i<j) {

  if(arr[i]%2==0) {

     i++;
  }

  else {

     swap(arr[i],arr[j]);
     j--;

  }

} 

I don't see how is your code O(N/2) . If array contains all odd or all even then one of the while loop will iterate through all n elements.

Instead of splitting code like you have done to get first odd/even numbers you can do something like quick sort, pivot element being last element and instead of separating less than and greater than you can check your criteria .

    int i = 0;
    int j = arr.length -1;

    while(i < j){
        if(arr[i]%2 != 0){
            i++; 
        }
        if(arr[j]%2 == 0){
            j--;
        }
        //swap
        arr[i] = arr[i] + arr[j];
        arr[j] = arr[i] - arr[j];
        arr[i] = arr[i] - arr[j];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM