給定一個存放整數的數組,重新排列數組使得數組左邊為奇數,右邊為偶數。
要求:空間復雜度O(1),時間復雜度為O(n)。
1 bool func(int n)
2 {
3 return (n&1)==0; // n%2 is more expensive
4 }
5
6 void group_oddeven(std::vector<int>& a, bool (*func)(int))
7 {
8 int i = 0, j = a.size()-1;
9 int buf = 0;
10 while (i < j) {
11 if (!func(a[i])) // odd, move forward
12 { i++; continue; }
13 if (func(a[j])) // even, move backward
14 { j--; continue; }
15
16 std::swap(a[i++], a[j--]);
17 }
18 }
19