1. 程式人生 > >《劍指offer》第二十一題(調整數組順序使奇數位於偶數前面)

《劍指offer》第二十一題(調整數組順序使奇數位於偶數前面)

有意 argv 條件 copy 判斷 \n str 方法 class

// 面試題21:調整數組順序使奇數位於偶數前面
// 題目:輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有
// 奇數位於數組的前半部分,所有偶數位於數組的後半部分。

#include <iostream>

void Reorder(int *pData, unsigned int length, bool(*func)(int));
bool isEven(int n);

// ====================方法一====================
//就是維護兩個指針,前者遇偶數且後者遇奇數時,就交換,直到兩個指針相遇
void ReorderOddEven_1(int
*pData, unsigned int length) { if (pData == nullptr || length == 0) return; int *pBegin = pData; int *pEnd = pData + length - 1; while (pBegin < pEnd) { // 向後移動pBegin,直到它指向偶數 while (pBegin < pEnd && (*pBegin & 0x1) != 0) pBegin
++; // 向前移動pEnd,直到它指向奇數 while (pBegin < pEnd && (*pEnd & 0x1) == 0) pEnd--; if (pBegin < pEnd) { int temp = *pBegin; *pBegin = *pEnd; *pEnd = temp; } } } // ====================方法二====================
//這個是將判斷條件拿到外面做一個函數,修改類似的題型時候,只要修改那個函數就行了 void ReorderOddEven_2(int *pData, unsigned int length) { Reorder(pData, length, isEven); } void Reorder(int *pData, unsigned int length, bool (*func)(int))//這個輸入就很有意思了,是按函數地址傳遞的函數,我理解中間的括號是因為優先級的原因 { if (pData == nullptr || length == 0) return; int *pBegin = pData; int *pEnd = pData + length - 1; while (pBegin < pEnd) { // 向後移動pBegin while (pBegin < pEnd && !func(*pBegin)) pBegin++; // 向前移動pEnd while (pBegin < pEnd && func(*pEnd)) pEnd--; if (pBegin < pEnd) { int temp = *pBegin; *pBegin = *pEnd; *pEnd = temp; } } } bool isEven(int n) { return (n & 1) == 0; } // ====================測試代碼==================== void PrintArray(int numbers[], int length) { if (length < 0) return; for (int i = 0; i < length; ++i) printf("%d\t", numbers[i]); printf("\n"); } void Test(const char* testName, int numbers[], int length) { if (testName != nullptr) printf("%s begins:\n", testName); int* copy = new int[length]; for (int i = 0; i < length; ++i) { copy[i] = numbers[i]; } printf("Test for solution 1:\n"); PrintArray(numbers, length); ReorderOddEven_1(numbers, length); PrintArray(numbers, length); printf("Test for solution 2:\n"); PrintArray(copy, length); ReorderOddEven_2(copy, length); PrintArray(copy, length); delete[] copy;//連測試都不忘刪啊,厲害 } void Test1() { int numbers[] = { 1, 2, 3, 4, 5, 6, 7 }; Test("Test1", numbers, sizeof(numbers) / sizeof(int)); } void Test2() { int numbers[] = { 2, 4, 6, 1, 3, 5, 7 }; Test("Test2", numbers, sizeof(numbers) / sizeof(int)); } void Test3() { int numbers[] = { 1, 3, 5, 7, 2, 4, 6 }; Test("Test3", numbers, sizeof(numbers) / sizeof(int)); } void Test4() { int numbers[] = { 1 }; Test("Test4", numbers, sizeof(numbers) / sizeof(int)); } void Test5() { int numbers[] = { 2 }; Test("Test5", numbers, sizeof(numbers) / sizeof(int)); } void Test6() { Test("Test6", nullptr, 0); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); system("pause"); return 0; }

《劍指offer》第二十一題(調整數組順序使奇數位於偶數前面)