java 将整数数组中前半部分的所有偶数和奇数移动到后半部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14441483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:16:44  来源:igfitidea点击:

move all even numbers on the first half and odd numbers to the second half in an integer array

javaalgorithm

提问by sonam

I had an interview question which i could not solve.

我有一个我无法解决的面试问题。

Write method (not a program) in Java Programming Language that will move all even numbers on the first half and odd numbers to the second half in an integer array.

Java 编程语言中的编写方法(不是程序),它将整数数组中前半部分的所有偶数和奇数移动到后半部分。

E.g. Input = {3,8,12,5,9,21,6,10}; Output = {12,8,6,10,3,5,9,21}.

例如输入 = {3,8,12,5,9,21,6,10}; 输出 = {12,8,6,10,3,5,9,21}。

The method should take integer array as parameter and move items in the same array (do not create another array). The numbers may be in different order than original array. This is algorithm test, so try to give as efficient algorithm as you can (possibly linear O(n) algorithm). Avoid using built in functions/API. *

该方法应将整数数组作为参数并在同一数组中移动项目(不要创建另一个数组)。这些数字可能与原始数组的顺序不同。这是算法测试,所以尽量给出尽可能有效的算法(可能是线性 O(n) 算法)。避免使用内置函数/API。*

Also some basic intro to what is data structure efficiency

还有一些基本的介绍什么是数据结构效率

回答by Emanuele Paolini

Keep two indices: one to the first odd number and one to the last even number. Swap such numbers and update indices.

保留两个索引:一个指向第一个奇数,一个指向最后一个偶数。交换这些数字并更新索引。

回答by JLRishe

(With a lot of help from @manu-fatto's suggestion) I believe this would do it:

(在@manu-fatto 的建议的帮助下)我相信这样做可以:

private static int[] OddSort(int[] items)
{
    int oddPos, nextEvenPos;
    for (nextEvenPos = 0; 
         nextEvenPos < items.Length && items[nextEvenPos] % 2 == 0;
         nextEvenPos++) { }
    // nextEvenPos is now positioned at the first odd number in the array, 
    // i.e. it is the next place an even number will be placed

    // We already know that items[nextEvenPos] is odd (from the condition of the 
    // first loop), so we'll start looking for even numbers at nextEvenPos + 1
    for (oddPos = nextEvenPos + 1; oddPos < items.Length; oddPos++)
    {
        // If we find an even number
        if (items[oddPos] % 2 == 0)
        {
            // Swap the values
            int temp = items[nextEvenPos];
            items[nextEvenPos] = items[oddPos];
            items[oddPos] = temp;
            // And increment the location for the next even number
            nextEvenPos++;
        }
    }

    return items;
}

This algorithm traverses the list exactly 1 time (inspects each element exactly once), so the efficiency is O(n).

该算法正好遍历列表 1 次(对每个元素只检查一次),因此效率为 O(n)。

回答by Saurabh Jain

// to do this in one for loop

// 在一个 for 循环中执行此操作

public static void evenodd(int[] integer) {

    int i = 0, temp = 0;
    int j = integer.length - 1;

    while (j >= i) {
        // swap if found odd even combo at i and j
        if (integer[i] % 2 != 0 && integer[j] % 2 == 0) {
            temp = integer[i];
            integer[i] = integer[j];
            integer[j] = temp;
            i++;
            j--;

        } else {
            if (integer[i] % 2 == 0) {
                i++;
            }
            if (integer[j] % 2 == 1) {
                j--;
            }

        }

    }
} 

回答by Sanj

@JLRishe,

@JLRishe,

Your algorithm doesn't maintain the order. For a simple example, say {1,5,2}, you will change the array to {2,5,1}. I could not comment below your post as I am a new user and lack reputations.

您的算法不维护顺序。举个简单的例子,比如 {1,5,2},你将数组更改为 {2,5,1}。由于我是新用户并且缺乏声誉,因此无法在您的帖子下方发表评论。

回答by sofa

public static void sorted(int [] integer) {

int i, j , temp;

for (i = 0;  i < integer.length;  i++) {

     if (integer[i] % 2 == 0) {
         for (j = i;  j < integer.length;  j++) {
              if (integer[j] % 2 == 1) {
                  temp = y[i];
                  y[i] = y[j];
                  y[j] = temp;
              }
          }
      }
      System.out.println(integer[i]);
}

public static void main(String args[]) {

       sorted(new int[]{1, 2,7, 9, 4}); 



}

}

The answer is 1, 7, 9, 2, 4.

答案是 1、7、9、2、4。

回答by Leon

Could it be that you were asked to implement a very basic version of the BubbleSort where the sort value of element e, where e = arr[i], = e%2==1 ? 1 : -1 ? Regards Leon

是否要求您实现一个非常基本的 BubbleSort 版本,其中元素 e 的排序值,其中 e = arr[i], = e%2==1 ?1:-1?问候里昂

回答by The Game

class Demo
{
public void sortArray(int[] a)
{
int len=a.length;
int j=len-1;
for(int i=0;i<len/2+1;i++)
{
if(a[i]%2!=0)
{
while(a[j]%2!=0 && j>(len/2)-1)
j--;
if(j<=(len/2)-1)
break;
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
for(int i=0;i<len;i++)
System.out.println(a[i]);
}

public static void main(String s[])
{
int a[]=new int[10];
System.out.println("Enter 10 numbers");
java.util.Scanner sc=new java.util.Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
new Demo().sortArray(a);
}
}

回答by maverick

private static void rearrange(int[] a) {
    int i,j,temp;
    for(i = 0, j = a.length - 1; i < j ;i++,j--) {
        while(a[i]%2 == 0 && i != a.length - 1) {
            i++;
        }
        while(a[j]%2 == 1 && j != 0) {
            j--;
        }
        if(i>j)
            break;
        else {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }       
}

回答by psk

public void sortEvenOddIntegerArray(int[] intArray){
    boolean loopRequired = false;
    do{
        loopRequired = false;
        for(int i = 0;i<intArray.length-1;i++){

            if(intArray[i] % 2 != 0 && intArray[i+1] % 2 == 0){

                int temp = intArray[i];
                intArray[i] = intArray[i+1];
                intArray[i+1] = temp;
                loopRequired = true;
            }
        }
    }while(loopRequired);
}

回答by Paul Hankin

You can do this with a single loop by moving odd items to the end of the array when you find them.

您可以通过在找到奇数项时将奇数项移动到数组末尾来使用单个循环来完成此操作。

static void EvensToLeft(int[] items) {
    int end = items.length;
    for (int i = 0; i < end; i++) {
        if (items[i] % 2) {
            int t = items[i];
            items[i--] = items[--end];
            items[end] = t;
        }
    }
}

Given an input array of length n the inner loop executes exactly n times, and computes the parity of each array element exactly once.

给定一个长度为 n 的输入数组,内循环正好执行 n 次,并且只计算每个数组元素的奇偶校验一次。