Title: Enter an array of integers to implement a function to adjust 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.
This question is actually very simple, of course, without considering the efficiency of the situation can be considered
We'll start the array from the previous index as long as the even number is found and the even number is removed.
The elements of the polygon are all moved forward one and then the even number is inserted at the end, so that after scanning again
All the even numbers are placed in the second half, and the odd ones are placed in the first half. But not efficient.
Every time you encounter an even number, you move all the elements that follow the even number plus the time to iterate over the array
The O (N2) is reached.
We can use two indexes or pointers, one to the end of the array to point to the beginning of the array.
1. The previous index moves backwards until an even number is encountered, followed by an index forward index until an odd number is encountered
2. Exchange of two elements
3. Repeat steps to know that the subsequent index meets the previous index or ends before the previous index.
The implementation code is as follows:
1#include <iostream>2 using namespacestd;3 4 voidRecorderoddeven (int*pdata,intlength)5 {6 intp1,p2;7p1=0;8p2=length-1;9 Ten while(p2>p1) One { A while(p2>p1&&pdata[p1]%2!=0) -p1++; - while(p2>p1&&pdata[p2]%2==0) thep2--; - - inttemp; -temp=PDATA[P1]; +pdata[p1]=PDATA[P2]; -pdata[p2]=temp; + } A } at - intMainintargcChar*argv[]) - { - intnums[5]={1,2,3,4,5}; - intLength=5; - Recorderoddeven (nums,length); in for(intI=0; i<length;i++) - { tocout<<nums[i]<<","; + } -cout<<Endl; the return 0; *}
Run:
The sword refers to the offer-. 14. Adjust the array order so that the odd digits precede the even number