# 《数据库》顺序有序表的合并

shoux9ian创建一个新表LC，通过比较指针pa和pb所指向的元素值，一次从表LA或表LB中“摘取”较小的元素插入到LC的最后，当其中一个表变为空时，说明此表的元素已经归并完毕，则需要将另一个非空表的剩余的元素一次插入到LC的最后面即可。

void Combine(SqList A,SqList B,SqList &C){
int *pa,*pb,*pc,*pa_last,*pb_last;
pa=A.elem;
pb=B.elem;
C.length=A.length+B.length;
C.elem=new int[C.length];
pc=C.elem;
pa_last=A.elem+A.length-1;
pb_last=B.elem+B.length-1;
while(pa<=pa_last&&pb<=pb_last){
if(*pa<=*pb){
*pc++=*pa++;
}else{
*pc++=*pb++;
}
}
while(pa<=pa_last){
*pc++=*pa++;
}
while(pb<=pb_last){
*pc++=*pb++;
}
}

C语言实现：

#include<stdio.h>
//#include<iostream>
//using namespace std;
#define MAX 100

typedef struct{
int *elem;//存储空间基地址
int length;
}SqList;

int InitList(SqList &L){
L.elem=new int[MAX];
if(!L.elem){
return 0;
}
L.length=0;
return 1;
}

void TraveList(SqList L){
for(int i=0;i<L.length;i++){
printf("%d ",L.elem[i]);
}
printf("\n");
}

void CreateList(SqList &L,int n){
printf("请输入表的元素:\n");
for(int i=0;i<n;i++){
printf("请输入第%d个元素值:",i+1);
int e;
scanf("%d",&e);
L.elem[i]=e;
L.length+=1;
}
}

void Combine(SqList A,SqList B,SqList &C){
int *pa,*pb,*pc,*pa_last,*pb_last;
pa=A.elem;
pb=B.elem;
C.length=A.length+B.length;
C.elem=new int[C.length];
pc=C.elem;
pa_last=A.elem+A.length-1;
pb_last=B.elem+B.length-1;
while(pa<=pa_last&&pb<=pb_last){
if(*pa<=*pb){
*pc++=*pa++;
}else{
*pc++=*pb++;
}
}
while(pa<=pa_last){
*pc++=*pa++;
}
while(pb<=pb_last){
*pc++=*pb++;
}
}

int main(){
SqList L1,L2;

if(InitList(L1)){
printf("L1初始化成功.\n");
}else{
printf("L2初始化失败!\n");
}

if(InitList(L2)){
printf("L2初始化成功!\n");
}else{
printf("L2初始化失败！\n");
}

printf("请输入L1的长度:");
int len1;
scanf("%d",&len1);
CreateList(L1,len1);
printf("遍历L1:\n");
TraveList(L1);

printf("请输入L2的长度:");
int len2;
scanf("%d",&len2);
CreateList(L2,len2);
printf("遍历表L2:\n");
TraveList(L2);

SqList L3;
Combine(L1,L2,L3);
printf("合并后的表:\n");
TraveList(L3);

}