算法实现数组前半部分为奇数,后半部分为偶数。
1 #include <iostream> 2 3 using namespace std; 4 5 6 void p(int a[], int n) 7 { 8 int *p,*q; 9 int tmp; 10 11 p= a; 12 q = a+n-1; 13 14 while(p<q) 15 { 16 while(p<q && *p%2==1) 17 p++; 18 while(p<q && *q%2==0) 19 q--; 20 if (p<q) 21 { 22 tmp = *p; 23 *p =*q; 24 *q = tmp; 25 } 26 } 27 } 28 29 30 int main() 31 { 32 int a[] = {1,2,4,7,3,5,4,5,3,1,7,8,6,6,9,2}; 33 34 p(a ,16); 35 36 for (int i=0; i<16; ++i) 37 { 38 cout<< a[i]<<" "; 39 } 40 41 cout<<endl; 42 43 return 0; 44 }