//Your program should make the minimum number of comparisons.
Time Complexity: O(n)
//Here we have a full program
1: #include<bits/stdc++.h>
2: using namespace std;
3: struct Pair
4: {
5: int min;
6: int max;
7: };
8: struct Pair getMinMax(int arr[], int n)
9: {
10: struct Pair minmax;
11: int i;
12: if (n == 1)
13: {
14: minmax.max = arr[0];
15: minmax.min = arr[0];
16: return minmax;
17: }
18: if (arr[0] > arr[1])
19: {
20: minmax.max = arr[0];
21: minmax.min = arr[1];
22: }
23: else
24: {
25: minmax.max = arr[1];
26: minmax.min = arr[0];
27: }
28: for(i = 2; i < n; i++)
29: {
30: if (arr[i] > minmax.max)
31: minmax.max = arr[i];
32: else if (arr[i] < minmax.min)
33: minmax.min = arr[i];
34: }
35: return minmax;
36: }
37: int main()
38: {
39: int arr[] = { 10, 11, 40, 41, 3, 9};
40: int arr_size = 6;
41: struct Pair minmax = getMinMax(arr, arr_size);
42: cout << "Minimum element is "
43: << minmax.min << endl;
44: cout << "Maximum element is "
45: << minmax.max;
46: return 0;
47: }
0 Comments
If you have any doubt then let me know.