C语言详解 之 集合的并

时间:2021-12-05 13:01:28

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;
}

 

 

 

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

 

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