根据我们昨天写的顺序表,今天我们将两个由小到大排列的顺序表,合并到第三个顺序表,依然是由小到大排列
#include "Seq_list.h"
void Small_Large_Merg(Seq_list*p_La, Seq_list*p_Lb, Seq_list*p_Lc)
{
assert(p_La != NULL&&p_Lb != NULL&&p_Lc != NULL);
p_Lc->Curr_Cap = p_La->Curr_Cap + p_Lb->Curr_Cap;
if (p_Lc->Curr_Cap > p_Lc->capacity)
{
Inc_Cap(p_Lc);
}
Elem_Type*pa = p_La->data;
Elem_Type*pb = p_Lb->data;
Elem_Type*pc = p_Lc->data;
Elem_Type*pa_Last = p_La->data + p_La->Curr_Cap;
Elem_Type*pb_Last = p_Lb->data + p_Lb->Curr_Cap;
while (pa < pa_Last&&pb < pb_Last)
{
if (*pa <= *pb)
{
*pc = *pa;
pc++;
pa++;
}
else
{
*pc = *pb;
pc++;
pb++;
}
}
while (pa < pa_Last)
{
*pc = *pa;
pc++;
pa++;
}
while (pb < pb_Last)
{
*pc = *pb;
pc++;
pb++;
}
}
int main()
{
int arr[] = { 1, 3, 5, 7, 9, 11, 39, 45 };
int len_a = sizeof(arr) / sizeof(arr[0]);
int brr[] = { 2, 4, 6, 8, 10, 12, 20, 30 };
int len_b = sizeof(brr) / sizeof(brr[0]);
Seq_list La, Lb, Lc;
Init_Seq_List(&La);
Init_Seq_List(&Lb);
Init_Seq_List(&Lc);
for (int i = 0; i < len_a; i++)
{
Tail_Insert(&La, arr[i]);
Tail_Insert(&Lb, brr[i]);
}
Print_Seq_List(&La);
Print_Seq_List(&Lb);
//La和Lb中的元素从小到大合并到Lc
Small_Large_Merg(&La, &Lb, &Lc);
Print_Seq_List(&Lc);
Dest_Seq_List(&La);
Dest_Seq_List(&Lb);
Dest_Seq_List(&Lc);
system("pause");
return 0;
}
合并两个有序数组
(1)
构建第三个数组
//合并两个有序数组
void Seq_Merg(int *nums1,int m,int *nums2,int n)
{
assert(nums1 != NULL&&nums2 != NULL);
int *tmp = (int *)malloc(sizeof(int)*(m + n));
if (tmp == NULL)
{
exit(1);
}
int i = 0;
int j = 0;
int k = 0;
while (i < m&&j < n)
{
tmp[k++] = nums1[i] <= nums2[j] ? nums1[i++] : nums2[j++];
}
while (i < m)
{
tmp[k] = nums1[i];
i++;
k++;
}
while (j < n)
{
tmp[k] = nums2[j];
k++;
j++;
}
for (int i = 0; i < m + n; i++)
{
nums2[i] = tmp[i];
}
free(tmp);
tmp = NULL;
}
int main()
{
int arr[3] = { 1, 5, 9 };
int brr[6] = { 2, 4, 12 };
Seq_Merg(arr, 3, brr, 3);
system("pause");
return 0;
}
(2)利用原有的数组
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void Merge_Two_Asc_Arr(int *arr, int arr_num, int m, int *brr, int brr_num, int n)
{
assert(arr != NULL);
assert(brr != NULL);
if (arr_num < m + n)
{
return;
}
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
while (i >= 0 && j >= 0)
{
if (arr[i] <= brr[j])
{
arr[k] = brr[j];
j--;
}
else
{
arr[k] = arr[i];
i--;
}
k--;
}
while (j >= 0)
{
arr[k] = brr[j];
k--;
j--;
}
for (int i = 0; i < m + n; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[10] = { 12, 23, 34, 78, 89 };
int brr[3] = { 23, 56, 99 };
Merge_Two_Asc_Arr(arr, 10, 5, brr, 3, 3);
system("pause");
return 0;
}