我试图在一次通过时分别将偶数和奇数分别分离到左侧和右侧。此外,我想确保这些数字按照顺序排序,这样整个逻辑将具有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--;
}
}
}
你的问题究竟是什么? – Skam
对O(n)中的数组进行排序 - 你不是要求太多吗? –
给定的数组是否已经排序? –