有序顺序表合并
将两个有序表合并为一个新的有序顺序表,并由函数返回结果顺序表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include "preset.h"
bool merge(SqList a, SqList b, SqList &c) { if (c.length < a.length + b.length) return false; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) { if (a.elem[i] <= b.elem[j]) { c.elem[k] = a.elem[i]; i++; k++; } else { c.elem[k] = b.elem[j]; j++; k++; } } while (i < a.length) { c.elem[k] = a.elem[i]; k++; i++; } while (j < b.length) { c.elem[k] = b.elem[j]; k++; j++; } c.length = a.length + b.length; return true; }
bool mergeList(SqList La, SqList Lb, SqList &Lc) { if (Lc.length < La.length + Lb.length) return false; int *pa = La.elem; int *pb = Lb.elem; int *pc = Lc.elem; Lc.length = La.length + Lb.length;
int *paLast = La.elem + La.length - 1; int *pbLast = Lb.elem + Lb.length - 1; while (pa <= paLast && pb <= pbLast) { if (*pa <= *pb) { *pc = *pa; pc++; pa++; } else { *pc = *pb; pc++; pb++; } }
while (pa <= paLast) *pc++ = *pa++; while (pb <= pbLast) *pc++ = *pb++; return true; }
int main() { SqList a = {{2, 2, 3, 3, 4, 5}, 6}; print(a); SqList b = {{4, 4, 4, 5, 5, 6, 8, 10}, 8}; print(b); SqList c; if (!merge(a, b, c)) cout << "合并出现错误" << endl; else print(c); return 0; }
|