第一种:

开辟一个一样大小的数组,遍历原数组的数据,把原数组奇数依次存放在新数组的前面,偶数存放在后面。

时间复杂度:O(n^2);

空间复杂度:O(n)

缺陷:效率太差

#include<stdio.h>#include<stdlib.h>voidAdjust(int*src,int*des,intn){intindex=0;for(intj=0;j<n;j++){if(src[j]%2){des[index]=src[j];index++;}}for(intj=0;j<n;j++){if(!(src[j]%2)){des[index]=src[j];index++;}}}voidtest(){inta1[10]={2,4,4,66,76,86,20,10,24,18};inta2[10]={1,3,5,35,15,13,17,19,17,21};inta3[10]={1,2,5,36,16,13,17,19,14,21};inta[10];Adjust(a3,a,sizeof(a3)/sizeof(a3[0]));for(inti=0;i<sizeof(a3)/sizeof(a3[0]);i++){printf("%d",a3[i]);}printf("\n");for(inti=0;i<sizeof(a)/sizeof(a[0]);i++){printf("%d",a[i]);}}intmain(){test();system("pause");return0;}

结果:

第二种:

利用两个指针,一个指向数组开始,一个指向数组末尾,指向数组开始的那个指针依次向后遍历,找到偶数立即停下来,指向数组末尾的那个指针向前遍历,找到奇数停下来,判断start<=end,,交换两个值。

#include<stdio.h>#include<stdlib.h>boolCheck(intnum){returnnum%2;}voidswap(int*a,int*b){inttmp=*a;*a=*b;*b=tmp;}voidAdjust(int*a,intn){intstart=0;intend=n-1;while(start<=end){while(Check(a[start])&&start<=end){start++;}while(!(Check(a[end]))&&start<=end){end--;}if(start<end){swap(&a[start],&a[end]);}}}voidtest(){inta1[10]={2,4,4,66,76,86,20,10,24,18};inta2[10]={1,3,5,35,15,13,17,19,17,21};inta3[10]={1,2,5,36,16,13,17,19,14,21};Adjust(a1,sizeof(a1)/sizeof(a1[0]));for(inti=0;i<sizeof(a1)/sizeof(a1[0]);i++){printf("%d",a1[i]);}printf("\n");Adjust(a2,sizeof(a2)/sizeof(a2[0]));for(inti=0;i<sizeof(a2)/sizeof(a2[0]);i++){printf("%d",a2[i]);}printf("\n");Adjust(a3,sizeof(a3)/sizeof(a3[0]));for(inti=0;i<sizeof(a3)/sizeof(a3[0]);i++){printf("%d",a3[i]);}}intmain(){test();system("pause");return0;}

结果: