From 7a7259f257f37a9f0c5b0b4998e87623c0ac06d2 Mon Sep 17 00:00:00 2001 From: Ritvik Garg <70766301+ritvik-garg@users.noreply.github.com> Date: Thu, 21 Oct 2021 19:02:01 +0530 Subject: [PATCH] Create Maximum and minimum of an array using minimum numbe.cppr of comparisons.cpp --- ...sing minimum numbe.cppr of comparisons.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 dsa-roadmaps/Love Babbar Questions/Arrays/Maximum and minimum of an array using minimum numbe.cppr of comparisons.cpp diff --git a/dsa-roadmaps/Love Babbar Questions/Arrays/Maximum and minimum of an array using minimum numbe.cppr of comparisons.cpp b/dsa-roadmaps/Love Babbar Questions/Arrays/Maximum and minimum of an array using minimum numbe.cppr of comparisons.cpp new file mode 100644 index 0000000..d61d230 --- /dev/null +++ b/dsa-roadmaps/Love Babbar Questions/Arrays/Maximum and minimum of an array using minimum numbe.cppr of comparisons.cpp @@ -0,0 +1,66 @@ +// C++ program of above implementation +#include +using namespace std; + +// Pair struct is used to return +// two values from getMinMax() +struct Pair +{ + int min; + int max; +}; + +struct Pair getMinMax(int arr[], int n) +{ + struct Pair minmax; + int i; + + // If there is only one element + // then return it as min and max both + if (n == 1) + { + minmax.max = arr[0]; + minmax.min = arr[0]; + return minmax; + } + + // If there are more than one elements, + // then initialize min and max + if (arr[0] > arr[1]) + { + minmax.max = arr[0]; + minmax.min = arr[1]; + } + else + { + minmax.max = arr[1]; + minmax.min = arr[0]; + } + + for(i = 2; i < n; i++) + { + if (arr[i] > minmax.max) + minmax.max = arr[i]; + + else if (arr[i] < minmax.min) + minmax.min = arr[i]; + } + return minmax; +} + +// Driver code +int main() +{ + int arr[] = { 1000, 11, 445, + 1, 330, 3000 }; + int arr_size = 6; + + struct Pair minmax = getMinMax(arr, arr_size); + + cout << "Minimum element is " + << minmax.min << endl; + cout << "Maximum element is " + << minmax.max; + + return 0; +}