郑州轻工业大学2020年数据结构练习集-6-3 合并两个有序数组 (20分)

要求实现一个函数merge,将长度为m的升序数组a和长度为n的升序数组b合并到一个新的数组c,合并后的数组仍然按升序排列。

函数接口定义:

void printArray(int* arr, int arr_size);           /* 打印数组,细节不表 */
void merge(int* a, int m, int* b, int n, int* c);  /* 合并a和b为c */

其中a和b是按升序排列的数组,m和n分别为数组a、b的长度;c为合并后的升序数组。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

void printArray(int* arr, int arr_size);          /* 打印数组,细节不表 */
void merge(int* a, int m, int* b, int n, int* c); /* 合并a和b为c */

int main(int argc, char const *argv[])
{
    int m, n, i;
    int *a, *b, *c;

    scanf("%d", &m);
    a = (int*)malloc(m * sizeof(int));
    for (i = 0; i < m; i++) {
        scanf("%d", &a[i]);
    }

    scanf("%d", &n);
    b = (int*)malloc(n * sizeof(int));
    for (i = 0; i < n; i++) {
        scanf("%d", &b[i]);
    }
    c = (int*)malloc((m + n) * sizeof(int));
    merge(a, m, b, n, c);
    printArray(c, m + n);

    return 0;
}

/* 请在这里填写答案 */

输入样例:

输入包含两行。 第一行为有序数组a,其中第一个数为数组a的长度m,紧接着m个整数。 第二行为有序数组b,其中第一个数为数组b的长度n,紧接着n个整数。

7 1 2 14 25 33 73 84
11 5 6 17 27 68 68 74 79 80 85 87

输出样例:

输出为合并后按升序排列的数组。

1 2 5 6 14 17 25 27 33 68 68 73 74 79 80 84 85 87

void merge(int* a, int m, int* b, int n, int* c){
    int a_index = 0, b_index = 0;
    int c_index = 0;
    while(a_index < m && b_index < n){
        if(*(a + a_index) < *(b + b_index)){
            *(c + c_index) = *(a + a_index);
            c_index++, a_index++;
        }else{
            *(c + c_index) = *(b + b_index);
            c_index++, b_index++;
        }
    }
    while(a_index < m){
        *(c + c_index) = *(a + a_index);
        c_index++, a_index++;
    }
    while(b_index < n){
        *(c + c_index) = *(b + b_index);
        c_index++, b_index++;
    }
}
发布了67 篇原创文章 · 获赞 22 · 访问量 7181

猜你喜欢

转载自blog.csdn.net/weixin_43906799/article/details/104536789