输入一个无序整数数组,调整数组中数字的顺序, 所有偶数位于数组的前半部分,使得所有奇数位于数组的后半部分。
要求时间复杂度为O(n)。
给定无序数组。
长度不超过1000000。
所有偶数位于数组的前半部分,所有奇数位于数组的后半部分。
如果有多个答案可以输出任意一个正确答案。
2 4 5 7 8 1
2 4 8 7 5 1
请自觉使用O(n)的算法。
#include <stdio.h>
#include <stdlib.h>
const int N = 1E6;
void swap(int* a, int* b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int main(const int argc, const char* const argv[]) {
int nums[N], numsSize = 0;
while (fscanf(stdin, "%d", nums + numsSize++) != EOF);
--numsSize;
int l = 0, r = numsSize - 1;
while (l < r) {
while (l < r && !(*(nums + l) & 1)) ++l;
while (l < r && *(nums + r) & 1) --r;
if (l < r) swap(nums + l++, nums + r--);
}
int i;
for (i = 0; i < numsSize; ++i)
fprintf(stdout, "%d ", *(nums + i));
return 0;
}