Permalink
Browse files

Improving binary search in find_lower() and find_upper(), may save a …

…few cycles.
  • Loading branch information...
1 parent cadd156 commit 39580c19dd2ff344d19ebda97efc70b4a5208598 @bingmann committed Feb 16, 2013
Showing with 8 additions and 16 deletions.
  1. +8 −16 include/stx/btree.h
View
@@ -1556,24 +1556,20 @@ class btree
{
if (n->slotuse == 0) return 0;
- int lo = 0,
- hi = n->slotuse - 1;
+ int lo = 0, hi = n->slotuse;
- while(lo < hi)
+ while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (key_lessequal(key, n->slotkey[mid])) {
- hi = mid - 1;
+ hi = mid; // key <= mid
}
else {
- lo = mid + 1;
+ lo = mid + 1; // key > mid
}
}
- if (hi < 0 || key_less(n->slotkey[hi], key))
- hi++;
-
BTREE_PRINT("btree::find_lower: on " << n << " key " << key << " -> (" << lo << ") " << hi << ", ");
// verify result using simple linear search
@@ -1603,24 +1599,20 @@ class btree
{
if (n->slotuse == 0) return 0;
- int lo = 0,
- hi = n->slotuse - 1;
+ int lo = 0, hi = n->slotuse;
- while(lo < hi)
+ while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (key_less(key, n->slotkey[mid])) {
- hi = mid - 1;
+ hi = mid; // key < mid
}
else {
- lo = mid + 1;
+ lo = mid + 1; // key >= mid
}
}
- if (hi < 0 || key_lessequal(n->slotkey[hi], key))
- hi++;
-
BTREE_PRINT("btree::find_upper: on " << n << " key " << key << " -> (" << lo << ") " << hi << ", ");
// verify result using simple linear search

0 comments on commit 39580c1

Please sign in to comment.