我的函数做什么->给定以矩阵形式排列的K个排序数组。任务是将它们合并。您需要完成mergeKArrays()函数,该函数带有2个参数,一个arr [k] [k] 2D矩阵,其中包含k个排序数组,以及一个整数k,表示排序数组的数量。该函数应返回一个指向合并的排序数组的指针。
int *mergeKArrays(int arr[][N], int k)
{
// int *merged = (int*)malloc(sizeof(int) * k * k);
// do merge sort, as individual are already sorted
// just need to merge the arrays
int *a = arr[0];
int size_c = 2 * k;
int nb = k;
int na = k;
int *b;
int *c;
int ia, ib, ic;
for(int i = 1; i <= k - 1; ++i)
{
// merge(x, arr[i], k * i, k)
b = arr[i];
c = malloc(sizeof(int) * size_c);
if(c == NULL) exit(0);
ia = ib = ic = 0;
while(ia < na && ib < nb)
{
if(a[ia] < b[ib])
{
c[ic++] = a[ia++];
}
else
{
c[ic++] = b[ib++];
}
}
if(ia != na)
{
for(int i = ia; i < na; ++i)
{
c[ic++] = a[i];
}
}
if(ib != nb)
{
for(int i = ib; i < nb; ++i)
{
c[ic++] = b[i];
}
}
a = c;
na = size_c;
// printArray(a, na);
// printf("\n");
size_c = size_c + k;
}
return a;
}