mardi 28 mars 2017

dichotomy faster than map?

map is not the fastest when the pairs are known, and a second needs to be found. Changing division by 2, with a a test of bit1, and division by 2 with >>1 are some improvements. but there might be some more other. What are they ?

int main (int argc, char* argv []) {
  std::pair<size_t, size_t> val_ [5] = {
    std::pair<size_t, size_t> (1, 3),
    std::pair<size_t, size_t> (2, 7), 
    std::pair<size_t, size_t> (5, 8),
    std::pair<size_t, size_t> (6, 22),
    std::pair<size_t, size_t> (10, 4)
  };
  size_t x (6);
  size_t a (0), b (5), med (0);
  while (a < b) {
    if (val_ [a].first == x) break;
    if (val_ [b-1].first <= x) {
      a = b-1;
      break;
    }
    med = ((b-a)&1 ? (a+b+1)>>1:(a+b)>>1); //faster than if ((b-a)%2) med = (a+b+1)/2; else med = (a+b)/2;
    if (med > b) break;
    if (val_ [med].first == x) {
      a = med;
      break;
    }
    if (val_ [med].first < x) a = med;
    else if (x < val_ [med].first) b = med;
    else {
      a = med;
      break;
    }
  }
  std::cout << "\tx --> " << val_ [a].second << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire