顺序有序表的合并
此为简单的非递减有序排列,以整数为例:
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 typedef int Elem; 5 6 typedef struct 7 { 8 Elem *elem; 9 int len; 10 }List; 11 12 void createList(List &L); //创建有序表 13 void traverse(List L); //遍历有序表 14 void mergeList(List La,List Lb,List &Lc);//合并有序表 15 16 int main() 17 { 18 List La,Lb,Lc; 19 20 createList(La); //创建La 21 createList(Lb); //创建Lb 22 23 traverse(La); //遍历 24 traverse(Lb); //遍历 25 26 mergeList(La,Lb,Lc);//合并 27 28 traverse(Lc); //遍历Lc 29 30 return 0; 31 } 32 33 void createList(List &L) 34 { 35 printf("input the length:\n"); //输入想要创建有序表的长度 36 scanf("%d",&L.len); 37 38 L.elem = (Elem*)malloc(sizeof(Elem)*L.len); //动态分配内存 39 40 for(int i=0;i<L.len;i++) 41 { 42 printf("input the %d data:\n",i); 43 scanf("%d",&L.elem[i]); //输入数据,创建有序表 44 } 45 46 } 47 48 void traverse(List L) 49 { 50 for(int i=0;i<L.len;i++) 51 { 52 printf("%d ",L.elem[i]); //遍历有序表 53 } 54 printf("\n"); 55 } 56 57 void mergeList(List La,List Lb,List &Lc) 58 { 59 Lc.len = La.len + Lb.len; //表Lc的长度; 60 Lc.elem = (Elem *)malloc(sizeof(Elem)*Lc.len); //为表Lc分配内存; 61 62 int *pa = La.elem; //指针pa,pb的初始值分别指向两个表的第一个元素; 63 int *pb = Lb.elem; 64 int *pc = Lc.elem; //pc指向新表的第一个元素; 65 66 int *pa_last = La.elem+La.len-1; //指针pa_last,pb_last指向两个表的最后一个元素 67 int *pb_last = Lb.elem+Lb.len-1; 68 69 while((pa<=pa_last)&&(pb<=pb_last)) //La,Lb未达到表尾时 70 { 71 if(*pa<=*pb) *pc++ = *pa++; //可理解为*pa = *pc;pc++;pa++;选择较小的值插入到Lc中; 72 else *pc++ = *pb++; 73 } 74 75 while(pa<=pa_last) *pc++ = *pa++; //Lb已到达表尾,依次将La的余下元素插入到Lc的最后; 76 while(pb<=pb_last) *pc++ = *pb++; //同上 77 78 }