思路:
头尾指针,向中间遍历,依据条件交换元素。
1 #include <iostream> 2 using namespace std; 3 4 void reOrder(int *pData, unsigned int len, bool (*func)(int)) 5 { 6 if(pData == NULL || len == 0) 7 return ; 8 9 int *pStart = pData; 10 int *pEnd = pData + len - 1; 11 12 while(pStart < pEnd) 13 { 14 while(pStart < pEnd && !func(*pStart)) 15 pStart++; 16 17 while(pStart < pEnd && func(*pEnd)) 18 pEnd--; 19 20 if(pStart < pEnd) 21 { 22 int temp = *pStart; 23 *pStart = *pEnd; 24 *pEnd = temp; 25 } 26 } 27 } 28 29 bool isEven(int n) 30 { 31 return (n & 1) == 0; 32 } 33 34 bool isPositive(int n) 35 { 36 return (n < 0) ? false : true; 37 } 38 39 int main() 40 { 41 cout<<"给定一个数组,期望奇数在前,偶数在后"<<endl; 42 int a[10] = {0,1,2,3,4,5,6,7,8,9}; 43 cout<<"原数组: "; 44 for(int i = 0; i < 10; i++) 45 cout<<a[i]<<" "; 46 cout<<endl; 47 48 reOrder(a, 10, isEven); 49 cout<<"重组后: "; 50 for(int i = 0; i < 10; i++) 51 cout<<a[i]<<" "; 52 cout<<endl<<endl; 53 54 cout<<"给定一个数组,期望负数在前,正数在后"<<endl; 55 int b[10] = {0,-1,2,3,-4,5,6,-7,-8,9}; 56 57 cout<<"原数组: "; 58 for(int i = 0; i < 10; i++) 59 cout<<b[i]<<" "; 60 cout<<endl; 61 62 reOrder(b, 10, isPositive); 63 64 cout<<"重组后: "; 65 for(int i = 0; i < 10; i++) 66 cout<<b[i]<<" "; 67 cout<<endl; 68 69 }
测试结果:
给定一个数组,期望奇数在前,偶数在后 原数组: 0 1 2 3 4 5 6 7 8 9 重组后: 9 1 7 3 5 4 6 2 8 0 给定一个数组,期望负数在前,正数在后 原数组: 0 -1 2 3 -4 5 6 -7 -8 9 重组后: -8 -1 -7 -4 3 5 6 2 0 9
时间: 2024-10-15 16:48:48