解题思路:
先将一个数组(默认第一个数组)拷贝进结果数组,然后将结果数组与待排序数组进行两两合并(相当于两个有序数组的合并)。注意在合并之前,要先将结果数组保存一下。
int * merge(int **values, int *sizes, int m) {
//先计算大小总的大小
int count = 0;
for (int i = 0; i < m; i++)
{
count += sizes[i];
}
int *merge = new int[count];
//count用来保存已排序元素的个数
count = sizes[0];
memcpy(merge, values[0], sizes[0] * 4);
for (int i = 1; i < m; i++)
{
int *temp = new int[count];
memcpy(temp, merge, count * 4);
int index = 0;
int a = 0;
int b = 0;
while (a < sizes[i] && b < count)
{
if (values[i][a] < temp[b])
{
merge[index] = values[i][a];
++a;
++index;
}
else
{
merge[index] = temp[b];
++b;
++index;
}
}
//将剩余元素拷贝
if (a == sizes[i])
{
while (b < count)
{
merge[index] = temp[b];
++b;
++index;
}
}
else
{
while (a < sizes[i])
{
merge[index] = values[i][a];
++a;
++index;
}
}
delete[] temp;
//更新count
count = index;
}
return merge;
}
int main()
{
int num1[] = { -123,-21,-1,1,3,13,16,19 };
int num2[] = { 2, 4, 6, 8, 10 ,342,5454,5654,5767};
int num3[] = { -1, 8, 9, 10, 11 ,34,54,56,76,865};
int num4[] = { 12, 23, 34, 45, 100,3454,5665,6765,675675 };
int *values[] = { num1, num2, num3, num4 };
int sizes[] = { sizeof(num1) / 4, sizeof(num2) / 4 ,sizeof(num3) / 4, sizeof(num4) / 4 };
int * res = merge(values, sizes,4);
for (int i = 0; i < sizeof(num1) / 4 + sizeof(num2) / 4 + sizeof(num3) / 4 + sizeof(num4) / 4; ++i)
{
cout << res[i] << " ";
}
cout << endl;
system("pause");
return 0;
}