Skip to content

Instantly share code, notes, and snippets.

@kireal
Forked from shivallan/MinMax
Last active August 29, 2015 14:19
Show Gist options
  • Save kireal/7c1f50337c67fbe238f4 to your computer and use it in GitHub Desktop.
Save kireal/7c1f50337c67fbe238f4 to your computer and use it in GitHub Desktop.
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <sys/time.h>
using namespace std;
std::pair<int, int> minimax (std::vector<long long> &v)
{
//std::vector<long long>::iterator max(std::max_element(v.begin(),v.end()));
//std::vector<long long>::iterator min(std::min_element(max,v.end()));
//std::pair<int, int> REZ(std::distance(v.begin(), max), std::distance(v.begin(), min));
long long max_diff(*v.begin() - *(v.begin() + 1));
long long max_element(*v.begin()), temp1(0), temp2(0);
std::vector<long long>::iterator max(v.begin()), min(v.begin() + 1), temp_max(v.begin());
for (std::vector<long long>::iterator i = v.begin() + 2; i != v.end(); ++i)
{
temp1 = max_element - *i;
temp2 = *i;
if(temp1 > max_diff)
{
max_diff = temp1;
min = i;
max = temp_max;
}
if(temp2 > max_element)
{
max_element = temp2;
temp_max = i;
}
}
std::pair<int, int> REZ(std::distance(v.begin(), max), std::distance(v.begin(), min));
return REZ;
}
int main()
{
timeval t1, t2;
double elapsedTime;
std::vector<long long> v(100000000); // vector for 100000000 elements
std::generate(v.begin(), v.end(), rand); // filling with random numbers
// start timer
gettimeofday(&t1, NULL);
std::pair<int, int> mm (minimax(v));
// stop timer
gettimeofday(&t2, NULL);
// compute and print the elapsed time in millisec
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
std::cout << "minimax -> " << elapsedTime << " ms.\n";
std::cout << "max v[" << mm.first << "] = " << *(v.begin() + mm.first) << "\n";
std::cout << "min v[" << mm.second << "] = " << *(v.begin() + mm.second) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment