LA和LB是两个int型数组,将他们合并为一个数组LC
(课本P20算法2.1)
#include<stdio.h>
#define len_LA 4
#define len_LB 7
//函数-获取元素
int getElem(int *list,int index)
{
return list[index-1];
}
//函数-插入元素
void ListInsert(int *list,int index,int value)
{
list[index]=value;
}
void main()
{
int LA[len_LA]={3,5,8,11};
int LB[len_LB]={2,6,8,9,11,15,20};
//int *Lc,i,j,k;
int *LC;
int i=1;
int j=1;
int k=0;
//计算合并所需长度
int len_LC=len_LA+len_LB;
//临时存取LA或者LB中的元素
int ai,bi;
//申请内存
LC=(int *)malloc(len_LC*sizeof(int));
//当LA和LB两个都没到结尾时,只要有一个到头了就结束循环
while((i<=len_LA)&&(j<=len_LB))
{
ai=getElem(LA,i);//获取LA元素
bi=getElem(LB,j);//获取LB元素
//判断两个元素大小把小的写入LC中
if(ai<=bi)//ai小插入ai
{
ListInsert(LC,++k,ai);
i++;
}else//bi插入bi
{
ListInsert(LC,++k,bi);
j++;
}
}
//LA没到头就把LA剩下数据写入LC中
while(i<=len_LA)
{
ai=getElem(LA,i);
ListInsert(LC,++k,ai);
i++;
}
//LB没到头就把LB剩下数据写入LC中
while(j<=len_LB)
{
bi=getElem(LB,j);
ListInsert(LC,++k,bi);
j++;
}
//循环查看合并效果
for(i=1;i<len_LC;i++)
{
printf("%d\n",LC[i]);
}
}