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

#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
******************************************/
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值