Skip to content

Commit 9e96a3f

Browse files
committed
perf: Optimize BTree search using binary search
This commit optimizes the search function in the BTree implementation by replacing the linear search with a binary search algorithm. This change significantly improves the search performance, especially for large trees. Implementation details: - Modified the `search` method in the `BTree` struct - Replaced the while loop with `binary_search` method on the `keys` vector Complexity analysis: - Previous implementation: O(n) per node, where n is the number of keys - New implementation: O(log n) per node Benchmark results: - Environment: MacOS 14.5, Apple M1 Pro, 32 GB RAM - Dataset: 1,000,000 random integers for insertion - Search: 1,000,000 searches for the key 500,000 - Before: - Insertion: 3.002587333s - Search: 2.334683584s - After: - Insertion: 2.998482583s - Search: 288.659458ms Note: Insertion time remains largely unchanged, as expected. All existing tests pass with the new implementation. Benchmark code is not included in this commit.
1 parent 3481e51 commit 9e96a3f

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/data_structures/b_tree.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -146,20 +146,16 @@ where
146146

147147
pub fn search(&self, key: T) -> bool {
148148
let mut current_node = &self.root;
149-
let mut index: isize;
150149
loop {
151-
index = isize::try_from(current_node.keys.len()).ok().unwrap() - 1;
152-
while index >= 0 && current_node.keys[index as usize] > key {
153-
index -= 1;
154-
}
155-
156-
let u_index: usize = usize::try_from(index + 1).ok().unwrap();
157-
if index >= 0 && current_node.keys[u_index - 1] == key {
158-
break true;
159-
} else if current_node.is_leaf() {
160-
break false;
161-
} else {
162-
current_node = &current_node.children[u_index];
150+
match current_node.keys.binary_search(&key) {
151+
Ok(_) => return true,
152+
Err(index) => {
153+
if current_node.is_leaf() {
154+
return false;
155+
} else {
156+
current_node = &current_node.children[index];
157+
}
158+
}
163159
}
164160
}
165161
}

0 commit comments

Comments
 (0)