我正在尝试将数组拆分为奇数
和偶数
数。请注意,在最终结果中对数字进行排序并不重要。我正在编译代码,输出包含一些错误。我的代码正确排列了 odd
数字,而 even
数字给我带来了一些麻烦。有人可以帮我安排偶数
数字吗?
基本上,我将 奇数
排列在数组的左侧,并在开头设置 oddPos = 0
; even
数字在右侧,定位从数组的最末端开始 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/