posts - 183,  comments - 10,  trackbacks - 0

使数组中的奇数位于偶数之前

从数组两端遍历,检测当前元素的奇偶性,条件允许时交换,直到两个索引交叉。


http://www.cppblog.com/jake1036/archive/2011/05/20/146798.html
 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 struct node
 7 {
 8     int m_;
 9 public:
10     node(int i = 0) : m_(i) {};
11     int m() const
12     {
13         return m_;
14     }
15 };
16 
17 bool operator < (const node& lhs, const node& rhs)
18 {
19     if (lhs.m() % 2 == 1 && rhs.m() % 2 == 0)
20     {
21         return true;
22     }
23     else if (lhs.m() % 2 == 0 && rhs.m() % 2 == 1)
24     {
25         return false;
26     }
27     else
28     {
29         return lhs.m() < rhs.m();
30     }
31 }
32 
33 bool operator == (const node& lhs, const node& rhs)
34 {
35     return lhs.m() == rhs.m();
36 }
37 
38 bool operator > (const node& lhs, const node& rhs)
39 {
40     return !(lhs < rhs || lhs == rhs);
41 }
42 
43 void foo(int a[], int n)
44 {
45     int left = 0, right = n - 1;
46     while (left < right)
47     {
48         while (left < right && (a[left] & 0x01== 1)
49         {
50             ++left;
51         }
52         while (right > left && (a[right] & 0x01== 0)
53         {
54             --right;
55         }
56         if (left < right)
57         {
58             a[left] ^= a[right];
59             a[right] ^= a[left];
60             a[left] ^= a[right];
61         }
62     }
63 }
64 
65 int main()
66 {
67     int a[] = {24681013579};
68     vector<node> test;
69     for (int i = 0; i != sizeof (a) / sizeof (*a); ++i)
70     {
71         test.push_back(node(a[i]));
72     }
73     foo(a, sizeof (a) / sizeof (*a));
74     for (int i = 0; i != sizeof (a) / sizeof (*a); ++i)
75     {
76         cout << a[i] << ' ';
77     }
78     cout << endl;
79 
80     sort(test.begin(), test.end());
81     for (vector<node>::size_type i = 0; i != test.size(); ++i)
82     {
83         cout << test[i].m() << ' ';
84     }
85     cout << endl;
86 
87     sort(test.begin(), test.end(), greater<node>());
88     for (vector<node>::size_type i = 0; i != test.size(); ++i)
89     {
90         cout << test[i].m() << ' ';
91     }
92     cout << endl;
93 }


posted on 2011-07-23 20:20 unixfy 阅读(201) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理