java - 对数组中的偶数和奇数进行排序

标签 java arrays

我正在尝试将数组拆分为奇数偶数 数。请注意,在最终结果中对数字进行排序并不重要。我正在编译代码,输出包含一些错误。我的代码正确排列了 odd 数字,而 even 数字给我带来了一些麻烦。有人可以帮我安排偶数数字吗?

基本上,我将 奇数 排列在数组的左侧,并在开头设置 oddPos = 0even 数字在右侧,定位从数组的最末端开始 evenPos = myArray.length - 1

public class EvenOddArray {

    public static void main(String[] args){

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


        int oddPos = 0;
        int evenPos = myArray.length - 1;

        for(int i = 0; i < myArray.length; i++){
            if(myArray[i] % 2 == 0){
                myArray[evenPos] = myArray[i];
                evenPos--;
            }
            else{
                myArray[oddPos] = myArray[i];
                oddPos++;
            }
        }

        for(int i = 0; i < myArray.length; i++){
            System.out.print(myArray[i] + " ");
        }
    }
}

输出:

1 3 5 7 2 4 6 6 4 2 

最佳答案

int current = 0;
int evenPos = myArray.Length - 1;
while (current < evenPos) {
    if (myArray[current] % 2 == 0) {
        swap(myArray, evenPos, current);
        evenPos--;
    } else {
        current++;
    }
}

压缩搞笑版:

for (int curPos=0, evenPos=myArray.length-1; curPos < evenPos;)
    if (myArray[curPos] % 2 == 0)
        swap(myArray, evenPos--, curPos);
    else
        curPos++;

更好玩的版本:

for (int curPos=0, evenPos=myArray.length-1; curPos < evenPos;)
    swap(myArray, curPos, myArray[curPos]%2==0 ? evenPos-- : curPos++);

解释:

You don't have to swap values when the number is odd. you only increase the current counter.

you can't use the for loop counter as an index to the array too. to not miss the numbers that gets swapped to the counter index not processed. this is the mistake that other answers didn't cover.

关于java - 对数组中的偶数和奇数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31769367/

相关文章:

java - 将 hibernate 投影结果映射到 Java POJO 模型

java - Bean 生命周期管理 Spring Boot

java - Thread.sleep 是模拟 HTTP 请求以进行测试的好方法吗?

c++ - 嵌入数据的多种类型

c - 数组指针错误?

javascript - 数组中的值被覆盖

java - 如何从abap接收使用RFC从java发送的表数据

java - 使用合并排序对(名称)进行排序

c - 读入短语并过滤掉字符以查找数字 C

java - Camel 队列中的线程 DSL 行为