#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#define MAXSIZE 100
typedef int elemType;
typedef struct {
elemType *data;
int length;
}sqList;
bool initList(sqList &L) {
L.data = new int[100];
if (!L.data) return false;
L.length = 0;
return true;
}
bool createList(sqList &L, int i) {
if (i < 1 || i > MAXSIZE) return false;
L.length = i;
for (int j = 0; j < i; j++) {
cout << "Input next value:";
cin >> L.data[j];
}
return true;
}
void showList(sqList &L) {
for (int i = 0; i < L.length; i++) {
cout << L.data[i] << " , ";
}
cout << endl;
}
void mergeList(sqList La, sqList Lb, sqList &Lc) {
Lc.length = La.length + Lb.length;
int i,j,k,flag;
i = j = k = flag = 0;
while (1) {
if (i == La.length) break;
if (j == Lb.length) {flag = 1;break;}
if (La.data[i] <= Lb.data[j]) Lc.data[k++] = La.data[i++];
else Lc.data[k++] = Lb.data[j++];
}
if (flag == 0) {
while (k < Lc.length) Lc.data[k++] = Lb.data[j++];
} else {
while (k < Lc.length) Lc.data[k++] = La.data[i++];
}
}
int main() {
sqList a, b, c;
if (!initList(a) || !initList(b) || !initList(c)) {
cout << "Init failed!";
return 0;
}
createList(a, 5);
createList(b, 7);
showList(a);
showList(b);
mergeList(a, b, c);
showList(c);
return 0;
}
Output:
Input next value:1
Input next value:3
Input next value:5
Input next value:7
Input next value:9
Input next value:2
Input next value:4
I
nput next value:6
Input next value:8
Input next value:10
Input next value:11
Input next value:12
1 , 3 , 5 , 7 , 9 ,
2 , 4 , 6 , 8 , 10 , 11 , 12 ,
1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ,
只有一层循环,循环次数为Lc.length时间复杂度为Ο(La.length+Lb.length)。