|
| 1 | +#include <stdio.h> |
| 2 | + |
| 3 | +/** |
| 4 | + * Function to find both the minimum and maximum elements in an array |
| 5 | + * |
| 6 | + * @param arr The array to search in |
| 7 | + * @param left The left index of the sub-array. |
| 8 | + * @param right The right index of the sub-array |
| 9 | + * @param min Pointer to store the minimum element |
| 10 | + * @param max Pointer to store the maximum element |
| 11 | + */ |
| 12 | + |
| 13 | +void MinAndMax(int arr[], int left, int right, int* min, int* max) { |
| 14 | + // if there is only one element in the sub-array, set it as both min and max |
| 15 | + if (left == right) { |
| 16 | + *min = *max = arr[left]; |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + // if there are two elements in the sub-array, compare and set min and max |
| 21 | + if (right - left == 1) { |
| 22 | + if (arr[left] < arr[right]) { |
| 23 | + *min = arr[left]; |
| 24 | + *max = arr[right]; |
| 25 | + } else { |
| 26 | + *min = arr[right]; |
| 27 | + *max = arr[left]; |
| 28 | + } |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + // calculate the middle index of the sub-array |
| 33 | + int mid = (left + right) / 2; |
| 34 | + int leftMin, leftMax, rightMin, rightMax; |
| 35 | + |
| 36 | + // recursively find min and max in the left and right sub-arrays |
| 37 | + MinAndMax(arr, left, mid, &leftMin, &leftMax); |
| 38 | + MinAndMax(arr, mid + 1, right, &rightMin, &rightMax); |
| 39 | + |
| 40 | + // update the minimum and maximum values |
| 41 | + *min = (leftMin < rightMin) ? leftMin : rightMin; |
| 42 | + *max = (leftMax > rightMax) ? leftMax : rightMax; |
| 43 | +} |
| 44 | + |
| 45 | +int main() { |
| 46 | + int arr[] = {10, 5, 20, 8, 15, 30, -12, 24}; |
| 47 | + int arrSize = sizeof(arr) / sizeof(arr[0]); |
| 48 | + |
| 49 | + int min, max; |
| 50 | + |
| 51 | + MinAndMax(arr, 0, arrSize - 1, &min, &max); |
| 52 | + |
| 53 | + printf("Minimum element: %d\n", min); |
| 54 | + printf("Maximum element: %d\n", max); |
| 55 | + |
| 56 | + return 0; |
| 57 | +} |
0 commit comments