设计一个程序,生成两个按值非递减有序排列的线性表LA和LB,再将LA和LB归并为一个新的线性表LC,且LC中的数据仍按值非递减有序排列,输出线性表LA、LB、LC。c语言实现
时间: 2023-11-10 15:27:31 浏览: 125
#include <stdio.h>
#include <stdlib.h>
void merge(int arr1[], int arr2[], int n1, int n2, int result[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < n1) {
result[k++] = arr1[i++];
}
while (j < n2) {
result[k++] = arr2[j++];
}
}
int main() {
int n1, n2, i;
printf("Enter the size of array 1: ");
scanf("%d", &n1);
printf("Enter the size of array 2: ");
scanf("%d", &n2);
int arr1[n1], arr2[n2], result[n1 + n2];
printf("Enter the elements of array 1 in non-decreasing order:\n");
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}
printf("Enter the elements of array 2 in non-decreasing order:\n");
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}
merge(arr1, arr2, n1, n2, result);
printf("\nArray 1:\n");
for (i = 0; i < n1; i++) {
printf("%d ", arr1[i]);
}
printf("\nArray 2:\n");
for (i = 0; i < n2; i++) {
printf("%d ", arr2[i]);
}
printf("\nMerged Array:\n");
for (i = 0; i < n1 + n2; i++) {
printf("%d ", result[i]);
}
return 0;
}
阅读全文