📜  C |数组|问题11(1)

📅  最后修改于: 2023-12-03 15:29:44.043000             🧑  作者: Mango

C 数组问题11

问题描述

设有一个大小为N的数组a,和一个大小为M的数组b。数组a中的元素按升序排列,数组b中的元素按升序排列。请写一个函数,将两个数组合并为一个升序排列的数组c。

函数声明
int* mergeArray(int a[], int n, int b[], int m);
参数说明
  • a : int类型数组,大小为N,表示升序排列的数组a。
  • n : int类型变量,表示数组a的大小。
  • b : int类型数组,大小为M,表示升序排列的数组b。
  • m : int类型变量,表示数组b的大小。
返回值

函数返回一个int类型的指针,指向合并后的升序排列的数组c。

实现思路

可以使用双指针法来实现该函数。定义两个指针分别指向数组a和数组b的第一个元素,比较两个指针指向的元素的大小,将小的元素放入新的数组c中,并将该指针向右移动一位,直到某个指针移动到数组末尾为止,此时将另一个数组中未遍历的元素全部放入数组c中。

代码实现
int* mergeArray(int a[], int n, int b[], int m) {
    int* c = (int*)malloc(sizeof(int) * (n + m));
    int i = 0, j = 0, k = 0;
    while (i < n && j < m) {
        if (a[i] < b[j]) {
            c[k++] = a[i++];
        } else {
            c[k++] = b[j++];
        }
    }
    while (i < n) {
        c[k++] = a[i++];
    }
    while (j < m) {
        c[k++] = b[j++];
    }
    return c;
}
测试样例
int main() {
    int n = 5, m = 3;
    int a[] = {1, 3, 5, 7, 9};
    int b[] = {2, 4, 6};
    int* c = mergeArray(a, n, b, m);
    for (int i = 0; i < n + m; i++) {
        printf("%d ", c[i]);
    }
    free(c);
    return 0;
}

输出结果为:1 2 3 4 5 6 7 9