# How to get maximum and minimum of an array using Sorting ?

## Approach:

One approach to find the maximum and minimum element in an array is to first sort the array in ascending order. Once the array is sorted, the first element of the array will be the minimum element and the last element of the array will be the maximum element.

## Algorithm:

1. Initialize an array.
2. Sort the array in ascending order.
3. The first element of the array will be the minimum element.
4. The last element of the array will be the maximum element.
5. Print the minimum and maximum element.

Below is the implementation of the above approach:

```// C++ implementation of the above approach
#include <algorithm>
#include <iostream>
using namespace std;

struct Pair {
int min;
int max;
};

Pair getMinMax(int arr[], int n)
{
Pair minmax;

sort(arr, arr + n);

minmax.min = arr;
minmax.max = arr[n - 1];

return minmax;
}

int main()
{
int arr[] = { 1000, 11, 445, 1, 330, 3000 };
int arr_size = sizeof(arr) / sizeof(arr);

Pair minmax = getMinMax(arr, arr_size);

cout << "Minimum element is " << minmax.min << endl;
cout << "Maximum element is " << minmax.max << endl;

return 0;
}

// This code is contributed by Tapesh(tapeshdua420)
```
```import java.util.Arrays;

class Pair {
public int min;
public int max;
}

class Main {
static Pair getMinMax(int arr[], int n) {
Pair minmax = new Pair();
Arrays.sort(arr);
minmax.min = arr;
minmax.max = arr[n - 1];
return minmax;
}

public static void main(String[] args) {
int arr[] = { 1000, 11, 445, 1, 330, 3000 };
int arr_size = arr.length;
Pair minmax = getMinMax(arr, arr_size);
System.out.println("Minimum element is " + minmax.min);
System.out.println("Maximum element is " + minmax.max);
}
}
```
```def getMinMax(arr):
arr.sort()
minmax = {"min": arr, "max": arr[-1]}
return minmax

arr = [1000, 11, 445, 1, 330, 3000]
minmax = getMinMax(arr)

print("Minimum element is", minmax["min"])
print("Maximum element is", minmax["max"])
```

Output

```Minimum element is 1
Maximum element is 3000```

### Code complexity Analysis:

The time complexity of this approach is O(n log n), where n is the number of elements in the array, as we are using a sorting algorithm. The space complexity is O(1), as we are not using any extra space.

Number of Comparisons:
The number of comparisons made to find the minimum and maximum elements is equal to the number of comparisons made during the sorting process. For any comparison-based sorting algorithm, the minimum number of comparisons required to sort an array of n elements is O(n log n). Hence, the number of comparisons made in this approach is also O(n log n). 5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%