The problem is divided into two parts, preferably with only two pointers.
For example, a pointer can be swept back from the head, and the other pointer is swept forward, ensuring that the first pointer always points to an odd number, the last pointer always points to an even number, and then the two are exchanged until the final two pointers are equal, that is, all the elements are scanned.
The code looks like this:
1 //Adjust the array order so that the odd digits are preceded by even numbers2#include <iostream>3 using namespacestd;4 voidFunction1 (int* Number, unsignedintlength)5 {6 intP1 =0;7 intP2 = length-1;8 while(p1<p2)9 {Ten while(P1 < P2 && (NUMBER[P1] &0x1) !=0)//P1 is not pointing to an even number, p1++ One++P1; A while(P1 < P2 && (NUMBER[P2] &0x1) !=1)//p2 points are not odd, p2--; ---P2; - if(P1 <p2)//Exchange two values, note: After the exchange of the next round must be two pointers will be closer to the middle the { - inttemp =NUMBER[P1]; -NUMBER[P1] =NUMBER[P2]; -NUMBER[P2] =temp; + } - } + } A voidPrint16 (int* Number, unsignedintlength)//Print function at { - for(inti =0; i < length; ++i) -cout << Number[i] <<" "; -cout <<Endl; - } - intMain16 () in { - inta[7] = {1,2,3,4,5,6,7 }; toFunction1 (A,7); +Print16 (A,7); -System"Pause"); the return 0; *}
The robustness of the code:
1#include <iostream>2 using namespacestd;3 voidPrint16 (int* Number, unsignedintlength)4 {5 for(inti =0; i < length; ++i)6cout << Number[i] <<" ";7cout <<Endl;8 }9 //reusability of codeTen voidReorder (int*pdata, unsignedintLengthBOOL(*func) (int)) One { A int*pbegin =PData; - int*pend = pData + Length-1; - while(Pbegin <pend) the { - while(Pbegin < Pend&&!func (*pbegin)) -++Pbegin; - while(Pbegin < Pend&&func (*pend)) +--Pend; - if(Pbegin <pend) { + inttemp = *Pbegin; A*pbegin = *Pend; at*pend =temp; - } - } - } - BOOLIsEven (intN) - { in return(N &1) ==0; - } to voidReorderoddeven (int*pdata, unsignedintlength) + { - Reorder (pData, length, isEven); the } * intMain16 () $ {Panax Notoginseng inta[7] = {1,2,3,4,5,6,7 }; -Function1 (A,7); thePrint16 (A,7); +Reorderoddeven (A,7); APrint16 (A,7); theSystem"Pause"); + return 0; -}
Adjusts the elements in the array so that the odd digits precede the array, and the even digits are at the back of the array