順序有序表的合並
此為簡單的非遞減有序排列,以整數為例:
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 }