This is an archive of the discontinued LLVM Phabricator instance.

fixing binary search for cases when element is not in array
ClosedPublic

Authored by aizatsky on Nov 15 2016, 3:05 PM.

Event Timeline

aizatsky updated this revision to Diff 78084.Nov 15 2016, 3:05 PM
aizatsky retitled this revision from to fixing binary search for cases when element is not in array.
aizatsky updated this object.
vitalybuka accepted this revision.EditedNov 15 2016, 4:37 PM
vitalybuka edited edge metadata.

Maybe:

TEST(SanitizerCommon, InternalBinarySearchVsLowerBound) {
  std::vector<int> data;
  auto create_item = [] (size_t i, size_t j) {
    auto v = i * 10000 + j;
    return ((v << 6) + (v >> 6) + 0x9e3779b9) % 100;
  };
  for (size_t i = 0; i < 1000; ++i) {
    data.resize(i);
    for (size_t j = 0; j < i; ++j) {
      data[j] = create_item(i, j);
    }

    std::sort(data.begin(), data.end());

    for (size_t j = 0; j < i; ++j) {
      int val = create_item(i, j);
      for (auto to_find : {val - 1, val, val + 1}) {
        uptr expected =
            std::lower_bound(data.begin(), data.end(), to_find) - data.begin();
        EXPECT_EQ(expected, InternalBinarySearch(data.data(), 0, data.size(),
                                                 to_find, std::less<int>()));
      }
    }
  }
}
This revision is now accepted and ready to land.Nov 15 2016, 4:37 PM

Added, the test. Thanks.

This revision was automatically updated to reflect the committed changes.