100题_29 调整数组顺序使奇数位于偶数
时间:2011-03-16 来源:小橋流水
输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。要求时间复杂度为O(n)。
代码
1 /*
2 * File: main.cpp
3 * Author: ziqiao
4 *
5 * Created on 2011年3月16日, 下午4:21
6 */
7
8 #include <cstdlib>
9 #include <iostream>
10
11 using namespace std;
12
13 bool isOdd(int x)
14 {
15 return x%2 == 1;
16 }
17
18 void exchange(int &a, int &b)
19 {
20 int temp = a;
21 a = b;
22 b = temp;
23 }
24
25 void evenOddSplit(int a[], int n)
26 {
27 int i, j;
28 i = 0;
29 j = n - 1;
30 while (i < j)
31 {
32 while (i < j && isOdd(a[i]))
33 i ++;
34 while (i < j && !isOdd(a[j]))
35 j --;
36 if (i < j)
37 exchange(a[i], a[j]);
38 }
39 }
40
41 /*
42 *
43 */
44 int main(int argc, char** argv)
45 {
46 int a[] = {3, 4, 7, 9, 10, 8, 4 , 1 ,2, 11};
47 evenOddSplit(a, 10);
48 for (int i = 0; i < 10; i++)
49 cout << a[i] << ' ';
50 cout << endl;
51 return 0;
52 }
这题跟之前的排好序列求和有点类似。我们可以永类似于快速排序的方法来做:用一个头指针和一个尾指针,向中间扫描,前面遇到偶数,后面遇到奇数暂停,交换这两个指针的指向,接着向中间扫描,直到两个指针相遇。
代码实现如下:

2 * File: main.cpp
3 * Author: ziqiao
4 *
5 * Created on 2011年3月16日, 下午4:21
6 */
7
8 #include <cstdlib>
9 #include <iostream>
10
11 using namespace std;
12
13 bool isOdd(int x)
14 {
15 return x%2 == 1;
16 }
17
18 void exchange(int &a, int &b)
19 {
20 int temp = a;
21 a = b;
22 b = temp;
23 }
24
25 void evenOddSplit(int a[], int n)
26 {
27 int i, j;
28 i = 0;
29 j = n - 1;
30 while (i < j)
31 {
32 while (i < j && isOdd(a[i]))
33 i ++;
34 while (i < j && !isOdd(a[j]))
35 j --;
36 if (i < j)
37 exchange(a[i], a[j]);
38 }
39 }
40
41 /*
42 *
43 */
44 int main(int argc, char** argv)
45 {
46 int a[] = {3, 4, 7, 9, 10, 8, 4 , 1 ,2, 11};
47 evenOddSplit(a, 10);
48 for (int i = 0; i < 10; i++)
49 cout << a[i] << ' ';
50 cout << endl;
51 return 0;
52 }
相关阅读 更多 +