icoding 排序 数组合并

数组合并

假设有 n 个长度为 k 的已排好序(升序)的数组,请设计数据结构和算法,将这 n 个数组合并到一个数组,且各元素按升序排列。即实现函数:

 void merge_arrays(const int* arr, int n, int k, int* output);

其中 arr 为按行优先保存的 n 个长度都为 k 的数组,output 为合并后的按升序排列的数组,大小为 n×k。

时间要求(评分规则),当 n > k 时:

  • 满分:时间复杂度不超过 O(n×k×log(n))
  • 75分:时间复杂度不超过 O(n×k×log(n)×k)
  • 59分:其它,如:时间复杂度为 O(n2×k2) 时。

答案

#include<stdio.h>
#include<stdlib.h>
#define R1 (row / 2)
#define R2 (row - row / 2)

void merge(int* f1, int* f2, int* output, int num1, int num2) {//queue the two Sequence tables in f,and store the put the result in output
    int i1 = 0, i2 = 0;
    while (i1 < num1 && i2 < num2) {
        if (f1[i1] <= f2[i2]) {
            output[i1+i2] = f1[i1];
            i1++;
        }
        else {
            output[i1 + i2] = f2[i2];
            i2++;
        }
    }
    while (i1 < num1) {
        output[i1+i2] = f1[i1];
        i1++;
    }
    while (i2 < num2) {
        output[i1+i2] = f2[i2];
        i2++;
    }
}

void merge_arrays(const int* arr, int row, int col, int* output) {
    int* f1 = (int*)malloc(R1 * col * sizeof(int));
    int* f2 = (int*)malloc(R2 * col * sizeof(int));
    const int* SA = &arr[0], * SB = &arr[row / 2 * col];
    if (SA == SB) {
        for (int i = 0; i < row * col; i++) {
            output[i] = SA[i];
        }
        return;
    }
    merge_arrays(SA, R1, col, f1);
    merge_arrays(SB, R2, col, f2);
    merge(f1,f2, output, R1 * col, R2*col);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

y0sh1ne

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值