Skip to content

Commit 309ce74

Browse files
committed
fix: find interpolation search keys in constant arrays
1 parent 5c39e87 commit 309ce74

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

‎Search/InterpolationSearch.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ export function interpolationSearch(arr, key) {
1818

1919
// Because the array is sorted the key must be between low and high
2020
while (low <= high && key >= arr[low] && key <= arr[high]) {
21+
// Equal endpoints mean every remaining element matches the key.
22+
if (arr[low] === arr[high]) {
23+
return low
24+
}
25+
2126
delta = (key - arr[low]) / (arr[high] - arr[low])
2227
position = low + Math.floor((high - low) * delta)
2328

‎Search/test/InterpolationSearch.test.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
11
import { interpolationSearch } from '../InterpolationSearch'
22

3+
test.each([
4+
[[7], 7, 0],
5+
[[7, 7, 7], 7, 0],
6+
[[-4, -4, -4], -4, 0],
7+
[[0, 0], 0, 0],
8+
[[7], 6, -1],
9+
[[7, 7, 7], 8, -1],
10+
[[], 7, -1]
11+
])('interpolationSearch(%j, %s) => %s', (array, key, expected) => {
12+
expect(interpolationSearch(array, key)).toBe(expected)
13+
})
14+
315
test('interpolationSearch([2, 6, 8, 14, 122, 169], 144) => -1', () => {
416
const array = [2, 6, 8, 14, 122, 169]
517
const key = 144

0 commit comments

Comments
 (0)