//#include <stdio.h>

int binsearch(double *key, double val, int keylength){ /*Random number function for integers*/
  int l = 0; /*Left hand limit*/
  int r = keylength - 1; /*Right hand limit*/
  int m; /*MIdpoint*/
  int k; /*Element containing value*/
  bool elementfound = false; /*True when the element containing the value has been found*/
  while (elementfound == false)
  {
    m = int(floor(float(l + r) / 2)); /*Calculate midpoint*/
    if (val<key[m]) /*If value lower than midpoint, shift the rand hand limit*/
    {
      r=m;
    }
    else /*Otherwise shift the left hand limit*/
    {
      l = m;
    }
    if (l == r - 1) /*Value lies in element between limits*/
    {
      elementfound = true;
    }
  }
  k = r - 1; /*Element index is index of upper limit when diregarding the index of the 0 value at the beginning of they key*/
  return k;
};
