Skip to content

Commit b2269fc

Browse files
committed
Address review edge cases in meta binary search
1 parent 3a48a80 commit b2269fc

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

Search/MetaBinarySearch.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ function metaBinarySearch(sortedArray, target) {
1212
}
1313

1414
const n = sortedArray.length
15-
const maxBit = Math.floor(Math.log2(n - 1 < 0 ? 0 : n - 1))
15+
const maxBit = Math.floor(Math.log2(Math.max(1, n - 1)))
1616

1717
let position = 0
1818
for (let bit = maxBit; bit >= 0; bit--) {
19-
const candidate = position | (1 << bit)
19+
const candidate = position + 2 ** bit
2020
if (candidate < n && sortedArray[candidate] <= target) {
2121
position = candidate
2222
}

Search/test/MetaBinarySearch.test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,8 @@ describe('Meta Binary Search', () => {
1818
test('returns -1 on empty input', () => {
1919
expect(metaBinarySearch([], 1)).toBe(-1)
2020
})
21+
22+
test('returns index for a matching element in a single-element array', () => {
23+
expect(metaBinarySearch([7], 7)).toBe(0)
24+
})
2125
})

0 commit comments

Comments
 (0)