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

来源:互联网 发布:码农网java入门 编辑:程序博客网 时间:2024/06/11 21:38
#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;}


 



阅读全文
0 0
原创粉丝点击