If an integer array is given, the array must be operated in the form of an odd number on the left and an even number on the right.
Idea: The Division Method of quick sorting was originally divided by comparison with a certain value. Change this algorithm policy to be divided based on the parity of each number.
Implementation 1:
/** Move the array, the even number to the right, and the odd number to the left * Method 1: Use a method similar to quick sorting * scan with a pointer, when an odd number is encountered, it is exchanged with the next element of the moved part (another pointer stores the right boundary of an odd number that has been moved) * scan once to complete, time complexity O (N ), space O (1) */void partition (INT arr [], int N) {int I =-1, end = n-1; For (Int J = start; j <= end; j ++) {If (ARR [J] % 2 = 1) {I ++; if (I! = J) {int temp = arr [I]; arr [I] = arr [J]; arr [J] = temp ;}}}}
Implementation 2:
Int partition (INT arr [], int N) {int I = 0; Int J = n-1; while (I <j) {While (I <J & (ARR [I] % 2 = 1) I ++; while (I <J & (ARR [J] % 2 = 0) j --; if (I <j) {swap (& arr [I], & amp; arr [J]) ;}} return I; // returns the index starting with an even number. You can leave it blank}
For PHP, the implementation method can be simpler. Directly scan the array. If it is an odd number, it is placed into the left array. Otherwise, right is placed into the right array and the result of array_merge is returned.
/** Method 2: For PHP, the processing method can be simpler. * scan the array directly. If it is an odd number, add the value to left_array. Otherwise, add the value to right_array. returns the merge result. * disadvantage: extra space required for O (n) */function partition ($ ARR) {$ left = array (); $ right = array (); for ($ J = 0; $ j <count ($ ARR); $ J ++) {if ($ arr [$ J] % 2 = 1) {$ left [] = $ arr [$ J];} else {$ right [] = $ arr [$ J] ;}} return array_merge ($ left, $ right );}