编写程序将两个有序的数组合并成一个有序数组c语言
时间: 2023-12-01 16:23:05 浏览: 98
C++实现两个有序数组的合并
#include <stdio.h>
void merge(int a[], int n, int b[], int m, int c[]) {
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] < b[j]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
while (i < n) {
c[k++] = a[i++];
}
while (j < m) {
c[k++] = b[j++];
}
}
int main() {
int a[] = {1, 3, 5, 7, 9};
int b[] = {2, 4, 6, 8, 10};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
int c[n + m];
merge(a, n, b, m, c);
printf("Merged array: ");
for (int i = 0; i < n + m; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
阅读全文