合并有序顺序表C++版

#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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容