Untitled
unknown
plain_text
4 days ago
1.5 kB
3
Indexable
#include <iostream> using namespace std; // Structure to store min and max struct MinMax { int min; int max; }; // Function to find min and max using the Tournament Method MinMax findMinMax(int arr[], int n) { MinMax result; int i; // If array has only one element if (n == 1) { result.min = result.max = arr[0]; return result; } // Initialize min and max based on first two elements if (arr[0] > arr[1]) { result.max = arr[0]; result.min = arr[1]; } else { result.max = arr[1]; result.min = arr[0]; } // Compare elements in pairs for (i = 2; i < n - 1; i += 2) { if (arr[i] > arr[i + 1]) { result.max = max(result.max, arr[i]); result.min = min(result.min, arr[i + 1]); } else { result.max = max(result.max, arr[i + 1]); result.min = min(result.min, arr[i]); } } // If there is an odd element left if (n % 2 == 1) { result.max = max(result.max, arr[n - 1]); result.min = min(result.min, arr[n - 1]); } return result; } // Main function to test the code int main() { int arr[] = {4, 7, 1, 9, 2, 6}; int n = sizeof(arr) / sizeof(arr[0]); MinMax result = findMinMax(arr, n); cout << "Minimum element: " << result.min << endl; cout << "Maximum element: " << result.max << endl; return 0; }
Editor is loading...
Leave a Comment