以下是修改后的代码,新增了一个函数用于将数组排序并输出:
#include <stdio.h>
int max(int a, int b) {
return a > b ? a : b;
}
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int findMax(int arr[], int left, int right) {
if (left == right) {
return arr[left];
} else {
int mid = (left + right) / 2;
int leftMax = findMax(arr, left, mid);
int rightMax = findMax(arr, mid + 1, right);
return max(leftMax, rightMax);
}
}
int main() {
int arr[] = {3, 5, 1, 7, 9, 4};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
printf("The sorted array is: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int maxNum = findMax(arr, 0, n - 1);
printf("The maximum number in the array is %d\n", maxNum);
return 0;
}
在原有代码的基础上,新增了一个归并排序的函数mergeSort,用于对数组进行排序。在主函数中调用该函数,然后输出排完序后的数组。