数组合并
假设有 n 个长度为 k 的已排好序(升序)的数组,请设计数据结构和算法,将这 n 个数组合并到一个数组,且各元素按升序排列。即实现函数:
void merge_arrays(const int* arr, int n, int k, int* output);
其中 arr 为按行优先保存的 n 个长度都为 k 的数组,output 为合并后的按升序排列的数组,大小为 n×k。
#include<stdio.h>
#include<stdlib.h>void merge_adjacent_arrays(const int* arr, int* arr2, int low, int mid, int high) {
int i = low, j = mid + 1, k = low;
while (i <= mid && j <= high) {
if (arr[i] < arr[j]) {
arr2[k] = arr[i];
i++;
}
else {
arr2[k] = arr[j];
j++;
}
k++;
}
while (i <= mid) {
arr2[k] = arr[i];
i++;
k++;
}
while (j <= high) {
arr2[k] = arr[j];
j++;
k++;
}
}void MSort(const int* arr, int low, int high, int col, int* output) {
int* arr2 = (int*)malloc((high - low + 1) * sizeof(int));
int mid;
if (high - low + 1 == col) {
for (int i = low; i <= high; i++) {
output[i] = arr[i];
}
}
else {
mid = (low + high) / col / 2 * col + col - 1;MSort(arr, low, mid, col, arr2);
MSort(arr, mid + 1, high, col, arr2);
merge_adjacent_arrays(arr2, output, low, mid, high);
}
free(arr2);
}void merge_arrays(const int* arr, int row, int col, int* output) {
MSort(arr, 0, row * col - 1, col, output);}
int main() {
const int arr[35] = {
29, 30, 38, 47, 57, 64, 66,
70, 73, 76, 79, 80, 88, 96,
71, 77, 81, 87, 94, 101, 110,
70, 74, 80, 87, 96, 100, 109,
35, 42, 51, 56, 61, 63, 71
};
int output[35];
merge_arrays(arr, 5, 7, output);
for (int i = 0; i <= 34; i++) {
printf("%d ", output[i]);
}
return 0;
}