C语言详解 之 集合的并

 

#include <stdio.h>
#include <math.h>

#define max 20
#define error -8
int sort_array(double x[],double y[],int x_num, int y_num, double z[]);

 int main()
{
    double x[max];
    double y[max];
    double z[max];
    int count_x=0;
    int count_y=0;
    double temp;
 
 printf("please input the sorted number/n");
    printf("input x Array elem or -8.0 ends:");
    scanf("%lf",&temp);
    while(-8.0 != temp)
    {
       x[count_x]=temp;
       count_x++;
    scanf("%lf",&temp);
     }


   printf("input y Array elem or -9.0 ends:");
    scanf("%lf",&temp);
    while(fabs(-9.0 - temp)>0.00001)
    {
       y[count_y]=temp;
       count_y++;
    scanf("%lf",&temp);
     }

  //sort(x,&x[count_x-1]);
  //sort(y,&y[count_y-1]);


  int count_z = sort_array(x, y, count_x,count_y,z);
   for(int i=0;i<count_z;i++)
    printf("%.1f  ",z[i]);

   return 0;  
}

int sort_array(double x[],double y[], int x_num, int y_num,double z[])
{
   int count_x=0,count_y=0;
   double *p=x,*q=y;
   int i=0;
   while(count_x<x_num && count_y<y_num)
   {
      if(*p<*q)
       {
          z[i]=*p;
          p++;
          count_x++;
          i++;
        }
      else if(*p>*q)
       {
          z[i]=*q;
          q++;
          count_y++;
          i++;
        }
      else
       {
          z[i]=*p;
          p++;
          q++;
          count_x++;
          count_y++;
          i++;
        }
   }
 
   int j;
   if(count_x == x_num)
    {
      for(j=count_y;j<y_num;j++)
      {
          z[i]=y[j];
          i++;
       }
    }
   else
   {
      for(j=count_x;j<x_num;j++)
      {
          z[i]=x[j];
          i++;
       }    
   }

   return i;
}

 

 

 

这段程序有意思的地方在于:在两个数组有序之后进行合并时,指针在其中的灵活使用。

 

在这里我首先想到的就是指针,总是觉得指针很好用!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值