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)
Use two pointers low and high to point to the head and tail of the array, respectively. The low pointer slides backwards, the high pointer slides forward, the low pointer is used to find the even number, the high pointer is used to find the cardinality, and the two are exchanged, which is similar to the quick sort
Public classAlgorithm {/**determine if the number num is odd*/ Public Static BooleanIsEven (intnum) { /**bit operations are faster than%*/ if(num & 1) = = 1) return true; return false; } Public Static voidReorderoddeven (int[] source) { intLow = 0; intHigh = Source.length-1; while(Low <=High ) { /**Find even numbers*/ while(IsEven (Source[low])) {++Low ; } /**Find Odd*/ while(!IsEven (Source[high])) { --High ; } if(Low <=High ) { /**Exchange*/ intTMP =Source[low]; Source[low]=Source[high]; Source[high]=tmp; } } } Public Static voidMain (String []args) {int[] Array =New int[]{2,4,5,6,3,8,1}; Algorithm.reorderoddeven (array); for(intNum:array) {System.out.println (num); } }}
Adjust the array order so that the odd digits are preceded by even numbers