12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- #include <stdio.h>
- #define MAX_SIZE 100
- void mergeArrays(int arr1[], int m, int arr2[], int n, int result[]) {
- int i = 0, j = 0, k = 0;
- // 归并两个有序数组
- while (i < m && j < n) {
- if (arr1[i] < arr2[j]) {
- result[k++] = arr1[i++];
- } else {
- result[k++] = arr2[j++];
- }
- }
- // 将剩余元素复制到结果数组中
- while (i < m) {
- result[k++] = arr1[i++];
- }
- while (j < n) {
- result[k++] = arr2[j++];
- }
- }
- int main() {
- int arr1[MAX_SIZE], arr2[MAX_SIZE], result[MAX_SIZE*2];
- int m, n;
- int i;
- // 输入第一个有序数组
- scanf("%d", &m);
- for (i = 0; i < m; i++) {
- scanf("%d", &arr1[i]);
- }
- // 输入第二个有序数组
- scanf("%d", &n);
- for (i = 0; i < n; i++) {
- scanf("%d", &arr2[i]);
- }
- // 合并两个有序数组
- mergeArrays(arr1, m, arr2, n, result);
- // 输出合并后的有序数组
- for (i = 0; i < m + n; i++) {
- printf("%d", result[i]);
- if (i < m + n - 1) {
- printf(" ");
- }
- }
- printf("\n");
- return 0;
- }
|