合并有序数组.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <stdio.h>
  2. #define MAX_SIZE 100
  3. void mergeArrays(int arr1[], int m, int arr2[], int n, int result[]) {
  4. int i = 0, j = 0, k = 0;
  5. // 归并两个有序数组
  6. while (i < m && j < n) {
  7. if (arr1[i] < arr2[j]) {
  8. result[k++] = arr1[i++];
  9. } else {
  10. result[k++] = arr2[j++];
  11. }
  12. }
  13. // 将剩余元素复制到结果数组中
  14. while (i < m) {
  15. result[k++] = arr1[i++];
  16. }
  17. while (j < n) {
  18. result[k++] = arr2[j++];
  19. }
  20. }
  21. int main() {
  22. int arr1[MAX_SIZE], arr2[MAX_SIZE], result[MAX_SIZE*2];
  23. int m, n;
  24. int i;
  25. // 输入第一个有序数组
  26. scanf("%d", &m);
  27. for (i = 0; i < m; i++) {
  28. scanf("%d", &arr1[i]);
  29. }
  30. // 输入第二个有序数组
  31. scanf("%d", &n);
  32. for (i = 0; i < n; i++) {
  33. scanf("%d", &arr2[i]);
  34. }
  35. // 合并两个有序数组
  36. mergeArrays(arr1, m, arr2, n, result);
  37. // 输出合并后的有序数组
  38. for (i = 0; i < m + n; i++) {
  39. printf("%d", result[i]);
  40. if (i < m + n - 1) {
  41. printf(" ");
  42. }
  43. }
  44. printf("\n");
  45. return 0;
  46. }