Skip to content

Commit 7dc4030

Browse files
authored
Merge pull request vJechsmayr#60 from AayusHTiw/new-branch
Interpolation Search
2 parents 7548527 + 2438282 commit 7dc4030

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

‎interpolation_search.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
function interpolationSearch(sortedArray, seekElement) {
2+
let leftIndex = 0;
3+
let rightIndex = sortedArray.length - 1;
4+
5+
while (leftIndex <= rightIndex) {
6+
const rangeDelta = sortedArray[rightIndex] - sortedArray[leftIndex];
7+
const indexDelta = rightIndex - leftIndex;
8+
const valueDelta = seekElement - sortedArray[leftIndex];
9+
10+
// If valueDelta is less then zero it means that there is no seek element
11+
// exists in array since the lowest element from the range is already higher
12+
// then seek element.
13+
if (valueDelta < 0) {
14+
return -1;
15+
}
16+
17+
// If range delta is zero then subarray contains all the same numbers
18+
// and thus there is nothing to search for unless this range is all
19+
// consists of seek number.
20+
if (!rangeDelta) {
21+
// By doing this we're also avoiding division by zero while
22+
// calculating the middleIndex later.
23+
return sortedArray[leftIndex] === seekElement ? leftIndex : -1;
24+
}
25+
26+
// Do interpolation of the middle index.
27+
const middleIndex = leftIndex + Math.floor(valueDelta * indexDelta / rangeDelta);
28+
29+
// If we've found the element just return its position.
30+
if (sortedArray[middleIndex] === seekElement) {
31+
return middleIndex;
32+
}
33+
34+
// Decide which half to choose for seeking next: left or right one.
35+
if (sortedArray[middleIndex] < seekElement) {
36+
// Go to the right half of the array.
37+
leftIndex = middleIndex + 1;
38+
} else {
39+
// Go to the left half of the array.
40+
rightIndex = middleIndex - 1;
41+
}
42+
}
43+
return -1;
44+
}
45+
46+
console.log(interpolationSearch([1,2,3,4,5], 3));

0 commit comments

Comments
 (0)