对一个数组,将数组中偶数从大到小排序,奇数从小到大排序,奇数和偶数交叉着放且输出数组第一位放奇数
若奇数和偶数不等长,则把剩下的直接放到数组中。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sorts(int a[],int n)
{
int i,j;
int tmp;
int cnt0=0,cnt1=0;
int cnt2;
/*int max_ou,min_ji;*/
int ou_num=0,ji_num=0;
int *r =a;
int ou_arr[100]={0};
int ji_arr[100]={0};
int *p_ou = ou_arr;
int *p_ji = ji_arr;
int *p = ou_arr;
int *q = ji_arr;
for(i=0;i<n;i++)
{
if(a[i]%2 == 0)//偶数
{
ou_num++;
*p_ou++ = a[i];
}
else//奇数
{
ji_num++;
*p_ji++ = a[i];
}
}
printf("ou_num=%d\n",ou_num);
printf("ji_num=%d\n",ji_num);
printf("before sorted oushu num is:");
for(i = 0;i< ou_num;i++)
printf("%d ",ou_arr[i]);
printf("\n");
printf("before sorted jishu num is:");
for(i = 0;i< ji_num;i++)
printf("%d ",ji_arr[i]);
printf("\n");
//偶数从大到小排列
for(i = 0;i< ou_num-1;i++)
for(j= i+1;j< ou_num;j++)
if(ou_arr[i]<ou_arr[j])
{
tmp = ou_arr[i];
ou_arr[i] = ou_arr[j];
ou_arr[j] = tmp;
}
printf("sorted oushu num is:");
for(i = 0;i< ou_num;i++)
printf("%d ",ou_arr[i]);
printf("\n");
//奇数从小到大排列
for(i = 0;i< ji_num-1;i++)
for(j= i+1;j< ji_num;j++)
if(ji_arr[i]>ji_arr[j])
{
tmp = ji_arr[i];
ji_arr[i] = ji_arr[j];
ji_arr[j] = tmp;
}
printf("sorted jishu num is:");
for(i = 0;i< ji_num;i++)
printf("%d ",ji_arr[i]);
printf("\n");
while(cnt0<ji_num && cnt1<ou_num)
{
*r++ = *q++;
cnt0++;
*r++ = *p++;
cnt1++;
}
cnt2 = cnt1;
if(cnt0 == ji_num)
{
while(cnt1<ou_num)
{
*r++ = *p++;
cnt1++;
}
}
if(cnt2 == ou_num)//这个地方有问题
{
while(cnt0<ji_num)
{
*r++ = *q++;
cnt0++;
}
}
}
int main(/*int argc, char **argv*/)
{
int i;
int a[14]={2,0,3,9,4,10,7,11,15,22,66,31,21,87};
sorts(a,14);
for(i=0;i<14;i++)
printf("%d ",a[i]);
getchar();
return 0;
}