an interesting algorithm to find min and max simultaneously


👍 g++ -std=c++11 min_n_max.cpp
👍 ./a.out
69 4 84 78 62 78 0 65 54 85 80 
s = 0
b = 85
👍 ./a.out
77 36 90 51 90 68 16 32 82 91 
s = 16
b = 91

👍 cat min_n_max.cpp 
#include <iostream>
#include <random>
#include <vector>
using namespace std;

int main() {
  default_random_engine e(time(0));
  uniform_int_distribution u(0,99); 
  vector<int> v;
  int s, b, i, n = 10 + u(e)%4;
  for (int i = 0; i < n; ++i)
    v.push_back(u(e));
  for (int i : v) cout << i << ' ';
  cout << endl;

  if (v.size() % 2 == 0) {
    if (v[0] < v[1]) {
      s = v[0];
      b = v[1];
    } else {
      s = v[1];
      b = v[0];
    }
    i = 2;
  } else { 
    s = b = v[0];
    i = 1;
  } 
  for (;i < v.size(); i+=2) {
    if (v[i] < v[i+1]) {
      if (v[i] < s) s = v[i];
      if (v[i+1] > b) b = v[i+1];
    } else {
      if (v[i+1] < s) s = v[i+1];
      if (v[i] > b) b = v[i];
    }
  }
  cout << "s = " << s << endl;
  cout << "b = " << b << endl;
}

    

9.1 Minimum and maximum p250 of