码迷,mamicode.com
首页 > 编程语言 > 详细

【剑指offer 面试题14】调整数组顺序使奇数位于偶数前面

时间:2015-06-20 18:22:46      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

思路:

  头尾指针,向中间遍历,依据条件交换元素。

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void reOrder(int *pData, unsigned int len, bool (*func)(int))
 5 {
 6     if(pData == NULL || len == 0)
 7         return ;
 8 
 9     int *pStart = pData;
10     int *pEnd = pData + len - 1;
11 
12     while(pStart < pEnd)
13     {
14         while(pStart < pEnd && !func(*pStart))
15             pStart++;
16 
17         while(pStart < pEnd && func(*pEnd))
18             pEnd--;
19 
20         if(pStart < pEnd)
21         {
22             int temp = *pStart;
23             *pStart = *pEnd;
24             *pEnd = temp;
25         }
26     }
27 }
28 
29 bool isEven(int n)
30 {
31     return (n & 1) == 0;
32 }
33 
34 bool isPositive(int n)
35 {
36     return (n < 0) ? false : true;
37 }
38 
39 int main()
40 {
41     cout<<"给定一个数组,期望奇数在前,偶数在后"<<endl;
42     int a[10] = {0,1,2,3,4,5,6,7,8,9};
43     cout<<"原数组: ";
44     for(int i = 0; i < 10; i++)
45         cout<<a[i]<<" ";
46     cout<<endl;
47 
48     reOrder(a, 10, isEven);
49     cout<<"重组后: ";
50     for(int i = 0; i < 10; i++)
51         cout<<a[i]<<" ";
52     cout<<endl<<endl;
53 
54     cout<<"给定一个数组,期望负数在前,正数在后"<<endl;
55     int b[10] = {0,-1,2,3,-4,5,6,-7,-8,9};
56 
57     cout<<"原数组: ";
58     for(int i = 0; i < 10; i++)
59         cout<<b[i]<<" ";
60     cout<<endl;
61 
62     reOrder(b, 10, isPositive);
63 
64     cout<<"重组后: ";
65     for(int i = 0; i < 10; i++)
66         cout<<b[i]<<" ";
67     cout<<endl;
68 
69 }

 

测试结果:

给定一个数组,期望奇数在前,偶数在后
原数组: 0 1 2 3 4 5 6 7 8 9
重组后: 9 1 7 3 5 4 6 2 8 0

给定一个数组,期望负数在前,正数在后
原数组: 0 -1 2 3 -4 5 6 -7 -8 9
重组后: -8 -1 -7 -4 3 5 6 2 0 9

 

【剑指offer 面试题14】调整数组顺序使奇数位于偶数前面

标签:

原文地址:http://www.cnblogs.com/tjuloading/p/4590752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!