Topic
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.
Analysis
The more straightforward way is to traverse each one, as long as it is even, take it out, will be the number of the next move forward, the even fill in the last square of the array, each encounter an even number will be moved O (n) numbers, then the total time complexity is O (n^2), inefficient, how to improve, You can observe the array if you want odd digits before even, that is, the order is reversed to change, from the two to the middle of the method is relatively simple, as long as the non-conforming to the odd before, then the reverse, or go to the middle continue to find the traversal, until all meet the conditions.
For example analysis, the array {1,2,3,4,5}, the final want is odd in front, even after the, here is not concerned about the problem of sorting, so, refer to the following process diagram can understand how to quickly adjust the order.
The end result is {1,5,3,4,2}
"Test Code"
#include <stdio.h>void Swap (int *P1,int *P2) {}void Reorder_odd_even (int *p,int length){int *P1= P;int *P2= p+length-1; while(P1<P2) { while((*P1&0x1!=0) && (P1<P2)) p1++; while((*P2&0x1) ==0&& (P1<P2)) p2--;if(P1<P2) {inttemp =*P1;*P1=*P2;*P2= temp; }}}voidPrint(int s[],int length){ for(inti =0; i<length; i++)printf("%d",s[i]);}intMain () {int s[ ] = {1,2,3,4,5}; Reorder_odd_even (s,5);Print(s,5);return 0;}
Extension
If this topic changes, such as the filter to let all can be divisible by 3 is not divisible by 3 in front, or to meet negative numbers in front of the non-negative, the above code corresponding parts of the filter conditions will change with the requirements, but, how can we make the program more universal, is similar to the problem with our code directly can be solved, do not always modify, can think of is to extract the filter conditions to become a function, in this test code only need to invoke the conditional function you want to judge can be, without change, so we have to write the following code:
#include <stdio.h>BOOL IsEven (intN) {return(n&1)==0;} void Reorder (int *p,int length, BOOL (*func)(int)){int *P1= P;int *P2= p+length-1; while(P1<P2) { while(!func (*P1) && (P1<P2)) p1++; while(Func (*P2) && (P1<P2)) p2--;if(P1<P2) {inttemp =*P1;*P1=*P2;*P2= temp; }}}void Reorder_odd_even (int s[],int length) {Reorder (s,length, IsEven);} voidPrint(int s[],int length){ for(inti =0; i<length; i++)printf("%d",s[i]);}intMain () {int s[ ] = {1,2,3,4,5}; Reorder_odd_even (s,5);Print(s,5);return 0;}
Adjust the array order so that the odd digits are preceded by even numbers