题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位予数组的后半部分。
完成基本功能的解法:
void ReorderOddEven( int pData[], const int length )
{
if( NULL == pData || length <= 0 )
return;
int *pBegin = pData, *pEnd = pData + length - 1;
while( pBegin < pEnd )
{
while( pBegin < pEnd && ( *pBegin & 0x1 ) == 1 ) pBegin++; // 向后移动指针 pBegin ,直到它指向偶数
while( pBegin < pEnd && ( *pEnd & 0x1 ) == 0 ) pEnd--; // 向前移动指针 pEnd , 直到它指向奇数
if( pBegin < pEnd )
{
int temp = *pBegin;
*pBegin = *pEnd;
*pBegin = temp;
}
}
}
考虑可扩展性的解法:
bool isEven( int n )
{
return ( n & 0x1 ) == 0;
}
void reorder( int pData[], const int length, bool (*func)(int) )
{
if( NULL == pData || length <= 0 )
return;
int *pBegin = pData, *pEnd = pData + length - 1;
while( pBegin < pEnd )
{
while( pBegin < pEnd && !func( *pBegin ) ) pBegin++; // 向后移动指针 pBegin ,直到它指向偶数
while( pBegin < pEnd && func( *pEnd ) ) pEnd--; // 向前移动指针 pEnd , 直到它指向奇数
if( pBegin < pEnd )
{
int temp = *pBegin;
*pBegin = *pEnd;
*pBegin = temp;
}
}
}
void reorderOddEven( int pData[], const int length )
{
reorder( pData, length, isEven );
}