-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_min_max.cpp
More file actions
30 lines (25 loc) · 962 Bytes
/
find_min_max.cpp
File metadata and controls
30 lines (25 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "find_min_max.h"
#include <algorithm>
auto FindMinMax::FindMinMax(const std::vector<int>& array) -> std::pair<int, int>
{
int global_min;
int global_max;
std::tie(global_min, global_max) = std::minmax(array[0], array[1]);
// compare 2 elements at a time
for (int i = 2; i < static_cast<int>(array.size()); i += 2)
{
// compare two adjacent elements
const auto& [local_min, local_max] = std::minmax(array[i], array[i + 1]);
// compare local min/max with global min/max
global_min = std::min(global_min, local_min);
global_max = std::max(global_max, local_max);
}
// if there are odd number of elements in the array,
// compare the last element with the existing global min/max
if (array.size() % 2 == 1)
{
global_min = std::min(global_min, array.back());
global_max = std::max(global_max, array.back());
}
return {global_min, global_max};
}