Question: Enter an integer array and implement a function to adjust the order of numbers in the array so that the even number is located in the second half of the array.
At first I thought of the Partitation function for fast sorting, so I wrote it in the form of fast sorting:
# Include <cstdio> # include <iostream> const int N = 100; void Partitation (int * A, int p, int r); int main (void) {int n, i; int A [N]; freopen ("in.txt", "r", stdin); while (scanf ("% d", & n )! = EOF) {for (I = 0; I <n; ++ I) {scanf ("% d", & A [I]);} Partitation (A, 0, n); for (I = 0; I <n; ++ I) {printf ("% d", A [I]);} printf ("\ n");} return 0;} // void Partitation (int * A, int p, int r) {int x = 1; int I = p-1; for (int j = p; j <r; ++ j) {if (1 = (A [j] & x )) {I ++; int nTemp = A [I]; A [I] = A [j]; A [j] = nTemp ;}}} /********** test ************ 102 4 7 6 1 3 9 7 5 6 7 105 1 3 4 56 1 3 5 2 4 66 2 6 4 1 3 522 332 1 231 2 11312 *********************** ***/
Another solution in the book is actually a fast Partitation, not just another version:
The general practice is to maintain two pointers. When the first pointer is initialized, it points to the first number of the array, which only moves backward. When the second pointer is initialized, it points to the last number of the array, it only moves forward. Before the occurrence of pointer C, the first pointer is always in front of the second pointer. If the first pointer points to an even number and the second Pointer Points to an odd number, we will exchange the two numbers.
Void ReorderOddEven (int * pData, unsigned int length) {if (pData = NULL | length = 0) {return;} int * pBegin = pData; int * pEnd = pData + length-1; while (pBegin <pEnd) {// move pBegin backward, until it points to an even number while (pBegin <pEnd & (* pBegin & 0x1 )! = 0) {pBegin ++;} // move the pEnd forward until it points to an odd while (pBegin <pEnd & (* pEnd & 0x1) = 0) {pEnd --;} if (pBegin <pEnd) {int temp = * pBegin; * pBegin = * pEnd; * pEnd = temp ;}}}