c语言 合并两个有序数组
时间: 2023-12-01 22:40:35 浏览: 88
以下是C语言合并两个有序数组的代码示例:
```c
#include <stdio.h>
void merge(int arr1[], int arr2[], int n1, int n2, int arr3[])
{
int i = 0, j = 0, k = 0;
// 合并两个数组
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j])
arr3[k++] = arr1[i++];
else
arr3[k++] = arr2[j++];
}
// 将剩余元素添加到合并后的数组中
while (i < n1)
arr3[k++] = arr1[i++];
while (j < n2)
arr3[k++] = arr2[j++];
}
int main()
{
int arr1[] = {1, 3, 5, 7};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {2, 4, 6, 8};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int arr3[n1 + n2];
merge(arr1, arr2, n1, n2, arr3);
printf("合并后的数组:\n");
for (int i = 0; i < n1 + n2; i++)
printf("%d ", arr3[i]);
return 0;
}
```
阅读全文