分治法求最大和次大值C语言
时间: 2024-01-13 10:04:46 浏览: 108
以下是分治法求最大和次大值的C语言代码:
#include <stdio.h>
void maxAndSecondMax(int arr[], int low, int high, int* max, int* secondMax)
{
int mid, max1, max2, secMax1, secMax2;
if (low == high) // base case
{
*max = arr[low];
*secondMax = -1; // if there's only one element, there's no second max
return;
}
if (high == low + 1) // only two elements
{
if (arr[low] > arr[high])
{
*max = arr[low];
*secondMax = arr[high];
}
else
{
*max = arr[high];
*secondMax = arr[low];
}
return;
}
mid = (low + high) / 2;
// recursively find max and second max in left half
maxAndSecondMax(arr, low, mid, &max1, &secMax1);
// recursively find max and second max in right half
maxAndSecondMax(arr, mid+1, high, &max2, &secMax2);
// combine the results
if (max1 > max2)
{
*max = max1;
if (secMax1 > max2)
{
*secondMax = secMax1;
}
else
{
*secondMax = max2;
}
}
else
{
*max = max2;
if (secMax2 > max1)
{
*secondMax = secMax2;
}
else
{
*secondMax = max1;
}
}
}
int main()
{
int arr[] = {1, 5, 8, 2, 6, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int max, secondMax;
maxAndSecondMax(arr, 0, n-1, &max, &secondMax);
printf("Max: %d\nSecond Max: %d\n", max, secondMax);
return 0;
}
阅读全文