Title Requirements:
Enter an array of integers, adjusting the order of the numbers in the array so that all the odd digits are in the first half of the array, and all the even digits are in the second half of the array.
Requires a time complexity of O (n).
Reference: Sword refers to the 14th question of offer.
Topic Analysis:
Using two pointers, Pbegin and pend,pbegin traverse backwards from the beginning, pEnd forward from the end, and when Pbegin encounters an even number and pEnd encounters odd numbers, swaps two digits and then continues the traversal until pbegin>pend, then ends.
Code implementation:
#include <iostream>using namespacestd;voidReorderoddeven (Char*pin,intlen);intMainvoid){ CharPstr[] ="4372173283475738495734858394"; cout<<"the original array is (in order of Chaos):"<< pStr <<Endl; Reorderoddeven (Pstr,strlen (PSTR)); cout<<"adjusted to (odd before and even after):"<< pStr <<Endl; return 0;}voidReorderoddeven (Char*pin,intLen) { if(Pin==null | | len<=0) return ; Char*pbegin =PIn; Char*pend = pin+len-1; while(pbegin<pEnd) { //move the pbegin backwards until the value is even while(Pbegin<pend && (*pbegin&0x01)!=0) Pbegin++; //move Pend forward until the value is odd while(Pbegin<pend && (*pend&0x01)==0) --pEnd; if(pbegin<pEnd) { Chartemp = *Pbegin; *pbegin = *pEnd; *pend =temp; } }}
Adjust the array order so that the odd digits are in front of even numbers "Microsoft interview 100 question 54th"