您的位置:首页 > 职场人生

剑指offer--面试题21:调整数组顺序使奇数位于偶数前面

2017-07-15 15:51 323 查看
#include <stdio.h>

void Reorder(int *A, unsigned int length, bool (*func)(int));
bool isEven(int n);
void swap(int *x,int *y);

void ReorderOddEven(int *pData, unsigned int length)
{
Reorder(pData, length, isEven);
}

void Reorder(int *A, unsigned int length, bool (*func)(int))
{
if(A == NULL || length <= 0)
return;

int *p1 = &A[0];  //A
int *p2 = &A[length - 1];//A+length-

while(p1 < p2)
{
// 向后移动pBegin
while(p1 < p2 && !func(*p1))
p1 ++;

// 向前移动pEnd
while(p1 < p2 && func(*p2))
p2 --;

if(p1 < p2)
swap(&*p1,&*p2);
}
}
bool isEven(int n)
{
return (n & 1) == 0;
}
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}

// ====================测试代码====================
void PrintArray(int numbers[], int length)
{
if(length < 0)
return;

for(int i = 0; i < length; ++i)
printf("%d\t", numbers[i]);

printf("\n");
}

int main()
{
int copy[8]={101,22,85,67,13,6,82,43};
PrintArray(copy, 8);
ReorderOddEven(copy, 8);
PrintArray(copy, 8);

return 0;
}




 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐