//调整数组顺序使奇数位于偶数前面:
void reorderOddEven(int* pData, unsigned int length){
if (pData == nullptr || length <= 0)
return;
int* pBegin = pData;
int* pEnd = pData + length - 1;
while (pBegin < pEnd){
while (pBegin != pEnd && (*pBegin & 0x1) == 1){
pBegin++;
}
while (pEnd != pBegin && (*pEnd & 0x1) == 0){
pEnd--;
}
if (pBegin < pBegin){
int temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
}
//可扩展性的写法:使用函数指针
void reorder(int* pData, unsigned int length, bool (*func)(int)){
if (pData == nullptr || length <= 0)
return;
int* pBegin = pData;
int* pEnd = pData + length - 1;
while (pBegin < pEnd){
while (pBegin < pEnd && !func(*pBegin))
pBegin++;
while (pEnd > pBegin && func(*pEnd))
pEnd--;
if (pBegin < pEnd){
int temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
}
bool isEven(int a){
return (a & 0x1);
}
void reorderOddEven(int* pData, unsigned int length){
reorder(pData, length, isEven);
}