我试图在一次传递中将偶数和奇数分别分离到左侧和右侧。此外,我想确保这些数字按 asc 顺序排序,这样整个逻辑的复杂度将达到 O(n)。
例如,如果我的输入是{9,8,2,3,11,10,1};
这个逻辑我将 o/p 实现为 {10 8 2 3 11 9 1 } 但我想确保我的输出在同一次传递中被排序为 { 2,8,10,1,3,9,11}。
static void segregateEvenOdd(int arr[]) {
/* Initialize left and right indexes */
int left = 0, right = arr.length - 1;
while (left < right) {
/* Increment left index while we see 0 at left */
while (arr[left] % 2 == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right] % 2 == 1 && left < right)
right--;
if (left < right) {
/* Swap arr[left] and arr[right] */
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
最佳答案
使用 Sort overload可以让你传递一个Comparator
。比较函数应该如下所示(伪代码):
Comparison(a, b)
{
if (Even(a) && !Even(b))
return -1; // a < b
if (Even(b) && !Even(a))
return 1; // a > b
// both are even, or both are odd.
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
关于java - 按顺序排列偶数和奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34892939/