入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

把两个升序数组按升序合并到另一个数组中

创建时间:2010-05-17 投稿人: 浏览次数:862

#include <stdio.h>
#include <conio.h>
#include <assert.h>

#define MAX 100  //define the maxium of array

/***************************************************************************************************
** Function prototype: int merge_onassending(const int *x, const int *y, int *z, int lena, int lenb)
** parameters:
** const int *x: used to accept an array1 sorted by assending order
** const int *y: used to accept an array2 sorted by assending order
** const int *z: used to accept an array3 to stored the merged result
** int lena    : the length of the array1
** int lenb    : the length of the array2
** Description : this function can merge array1 with array2 to array3
** Returns:
** an interger number of the elements of array3
** ***************************************************************************************************/
int merge_onassending(const int *x, const int *y, int *z, int lena, int lenb)
{
 assert(x); // to check the pointer
 assert(y);
 assert(z);

 int i=0,j=0,k=0;

 while( i<lena && j<lenb )     /*x[i] 可以用 *(x+i) 替换,其他类同*/
 {
  if(x[i] < y[j]) z[k++]=x[i++];      
  else if(x[i] > y[j]) z[k++]=y[j++];
     else
     {
    z[k++] = x[i++];
       j++;
     }
 }
 while(i < lena) z[k++] = x[i++];
 while(j < lenb) z[k++] = y[j++];

 return k;        // the number of elements of the merged array
}
int main(void)
{
 int i;
 int lena,lenb,lenc;
    int a[]={2,7,9,11,13,15,17,19,40};
 int b[]={2,7,6,8,10};
 int c[MAX];

 lena = sizeof(a) / sizeof(a[0]);
 lenb = sizeof(b) / sizeof(b[0]);

 lenc =  merge_onassending( a, b, c, lena, lenb);

 for( i=0; i < lenc; i++)   printf("%d ", c[i]);

 getch();
 return 0;
}
/*****************************************
** date: 2010/5/17
** class :  数组处理
** vision: v1.0
******************************************/
 

阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像