合并多个数组(合并两个数组)
合并多个数组(合并两个数组)
问题:array1 array2为两个有序的升序数组,将array1和array2合并为一个升序有序数组
1.合并两个有序数组array1 array2,借助数组array3。从头开始,将array1的第一个元素和array2的第一个元素比较,小的放到array3中。
#include<stdio.h>
#define MAX 15
//合并两个有序数组a b,借助数组c
void MergeArray(int array1[] int len1 int array2[] int len2 int array3[] int len3)
{
if (len3 < len1 len2)
return;
int index1 = 0 index2 = 0 index3 = 0;
while (index1 < len1&&index2 < len2)
{
if (array1[index1] < array2[index2])
{
array3[index3 ] = array1[index1 ];
}
else
{
array3[index3 ] = array2[index2 ];
}
}
while (index1 < len1)
{
array3[index3 ] = array1[index1 ];
}
while (index2 < len2)
{
array3[index3 ] = array2[index2 ];
}
return;
}
int main()
{
int array1[] = { 1 3 5 7 9 };
int array2[] = { 2 4 6 8 9 };
int len1 = sizeof(array1) / sizeof(int);
int len2 = sizeof(array2) / sizeof(int);
int array3[MAX];
MergeArray(array1 len1 array2 len2 array3 MAX);
for (int i = 0; i < len1 len2; i )
{
printf("%d " array3[i]);
}
}
2.假设array1足够大,能够放下array1和array2,从后往前比较array1,和array2,大的元素放到最右边。
#include<stdio.h>
#define MAX 15
//合并两个有序数组array1 array2 从后往前比较,将array1和array2最后一个元素比较,大的放到len1 len2-1
void MergeArray(int array1[] int len1 int array2[] int len2)
{
int index1 = len1 - 1;
int index2 = len2 - 1;
int index = len1 len2 - 1;
while (index1 >= 0&&index2 >= 0)
{
if (array1[index1] > array2[index2])
{
array1[index--] = array1[index1--];
}
else
{
array1[index--] = array2[index2--];
}
}
while (index1 >= 0)
{
array1[index--] = array1[index1--];
}
while (index2 >= 0)
{
array1[index--] = array2[index2--];
}
return;
}
int main()
{
int array1[MAX] = {1 3 5 7 9 10 };
int array2[] = { 2 4 6 8 9 };
int len2 = sizeof(array2) / sizeof(int);
MergeArray(array1 6 array2 len2);
for (int i = 0; i < 6 len2; i )
{
printf("%d " array1[i]);
}
}