思路:
头尾指针,向中间遍历,依据条件交换元素。
#include <iostream>
using namespace std; void reOrder(int *pData, unsigned int len, bool (*func)(int))
{
if(pData == NULL || len == )
return ; int *pStart = pData;
int *pEnd = pData + len - ; while(pStart < pEnd)
{
while(pStart < pEnd && !func(*pStart))
pStart++; while(pStart < pEnd && func(*pEnd))
pEnd--; if(pStart < pEnd)
{
int temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
}
}
} bool isEven(int n)
{
return (n & ) == ;
} bool isPositive(int n)
{
return (n < ) ? false : true;
} int main()
{
cout<<"给定一个数组,期望奇数在前,偶数在后"<<endl;
int a[] = {,,,,,,,,,};
cout<<"原数组: ";
for(int i = ; i < ; i++)
cout<<a[i]<<" ";
cout<<endl; reOrder(a, , isEven);
cout<<"重组后: ";
for(int i = ; i < ; i++)
cout<<a[i]<<" ";
cout<<endl<<endl; cout<<"给定一个数组,期望负数在前,正数在后"<<endl;
int b[] = {,-,,,-,,,-,-,}; cout<<"原数组: ";
for(int i = ; i < ; i++)
cout<<b[i]<<" ";
cout<<endl; reOrder(b, , isPositive); cout<<"重组后: ";
for(int i = ; i < ; i++)
cout<<b[i]<<" ";
cout<<endl; }
测试结果:
给定一个数组,期望奇数在前,偶数在后
原数组:
重组后: 给定一个数组,期望负数在前,正数在后
原数组: - - - -
重组后: - - - -