案例
數組內容:3 4 4 6 8 2 1 1 1
調換奇偶:3 1 1 1 8 2 4 4 6
思路
源於快速排序
方式1

參考代碼
#include <iostream> #include <cstring> using namespace std; bool IsOdd(int num) { return num % 2 == 1 ? true : false; } bool changeArray(int *a, int size) { if(size <= 0) return false; int oddPartition = -1; int cur = 0; for(; cur < size; ++cur) { if(IsOdd(a[cur])) { if(oddPartition + 1 != cur) { int tmp = a[oddPartition+1]; a[oddPartition]= a[cur]; a[cur] = tmp; } ++oddPartition; } } return true; } int main() { int a[] = {3, 4, 4, 6, 8, 2, 1, 1, 1}; int size = sizeof(a) / sizeof(int); for(int i = 0; i < size; ++i) cout << a[i] << " "; cout << endl; changeArray(a, size); for(int i = 0; i < size; ++i) cout << a[i] << " "; cout << endl; }
方式2

參考代碼
#include <iostream> #include <cstring> using namespace std; bool IsOdd(int num) { return num % 2 == 1 ? true : false; } bool changeArray(int *a, int size) { if(size <= 0) return false; int beg = 0, end = size -1; while(beg < end) { while(beg < end && IsOdd(a[beg])) ++beg; while(beg < end && !IsOdd(a[end])) --end; if(beg < end) { int tmp = a[beg]; a[beg] = a[end]; a[end] = tmp; } } return true; } int main() { int a[] = {3, 4, 4, 6, 8, 2, 1, 1, 1}; int size = sizeof(a) / sizeof(int); for(int i = 0; i < size; ++i) cout << a[i] << " "; cout << endl; changeArray(a, size); for(int i = 0; i < size; ++i) cout << a[i] << " "; cout << endl; }
擴展
不是奇偶問題,別掉條件
比如正負,需要把IsOdd()函數換成判斷正負的函數;
比如被5整除,需要把IsOdd()函數換成判斷被5整除的函數;
。。。。。。
這是一類問題,可以給出一個模式來解決。如下
#include <iostream> using namespace std; bool isEven(int val) { return ((val & 0x1) == 0) ? true : false; } void ReOrder(int *a, int size, bool (*func)(int)) { if (a == NULL || size <= 0) return; int beg = 0, end = size-1; while (beg < end) { while (beg < end && !func(a[beg])) ++beg; while (beg < end && func(a[end])) --end; if (beg < end) swap(a[beg], a[end]); } } void ReOrderOddEven(int *a, int size) { ReOrder(a, size, isEven); } void tranverse(int *a, int size) { if (a == NULL || size <= 0) return; for (int i = 0; i < size; ++i) cout << a[i] << " "; cout << endl; } int main() { int a[] = {3, 2, 5, 2, 8, 3, 3, 0, 9}; int size = sizeof(a) / sizeof(int); tranverse(a, size); ReOrderOddEven(a, size); tranverse(a, size); }
