帮我写一个C语言程序表示如下:顺序有序表la和lb的元素值非递减排列 归并la和lb得到新的程序有序表lc lc的元素也按值非递减排列
时间: 2023-04-04 10:02:01 浏览: 75
好的,以下是C语言程序:
```
#include <stdio.h>
void merge(int la[], int lb[], int lc[], int na, int nb) {
int i = , j = , k = ;
while (i < na && j < nb) {
if (la[i] <= lb[j]) {
lc[k++] = la[i++];
} else {
lc[k++] = lb[j++];
}
}
while (i < na) {
lc[k++] = la[i++];
}
while (j < nb) {
lc[k++] = lb[j++];
}
}
int main() {
int la[] = {1, 3, 5, 7, 9};
int lb[] = {2, 4, 6, 8, 10};
int lc[10];
merge(la, lb, lc, 5, 5);
for (int i = ; i < 10; i++) {
printf("%d ", lc[i]);
}
return ;
}
```
这个程序可以将两个有序表la和lb合并成一个新的有序表lc,其中la和lb的元素值非递减排列,lc的元素也按值非递减排列。
相关问题
已知线性表LA和LB中的元素按值非递减有序排列,现要求将LA和LB归并为一个新的线性表LC,且LC中的元素仍按值非递减有序排列。请用c语言程序实现上述代码。
以下是C语言程序实现上述代码:
#include <stdio.h>
void merge(int LA[], int LB[], int LC[], int lenA, int lenB) {
int i = 0, j = 0, k = 0;
while (i < lenA && j < lenB) {
if (LA[i] <= LB[j]) {
LC[k++] = LA[i++];
} else {
LC[k++] = LB[j++];
}
}
while (i < lenA) {
LC[k++] = LA[i++];
}
while (j < lenB) {
LC[k++] = LB[j++];
}
}
int main() {
int LA[] = {1, 3, 5, 7, 9};
int LB[] = {2, 4, 6, 8, 10};
int lenA = sizeof(LA) / sizeof(int);
int lenB = sizeof(LB) / sizeof(int);
int LC[lenA + lenB];
merge(LA, LB, LC, lenA, lenB);
printf("Merged array: ");
for (int i = 0; i < lenA + lenB; i++) {
printf("%d ", LC[i]);
}
printf("\n");
return 0;
}
设计一个程序,生成两个按值非递减有序排列的线性表LA和LB,再将LA和LB归并为一个新的线性表LC,且LC中的数据仍按值非递减有序排列,输出线性表LA、LB、LC。c语言实现
#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;
}