Skip to content

Commit

Permalink
Merge pull request #1 from Kanai2003/InterpolationSearch
Browse files Browse the repository at this point in the history
Create InterpolationSearch.js
  • Loading branch information
Kanai2003 authored Oct 20, 2023
2 parents 66fe69a + 8f5e2bd commit 5382dc1
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions algorithms/searching/InterpolationSearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class InterpolationSearch {
constructor(arr) {
this.arr = arr;
}

search(target) {
let low = 0;
let high = this.arr.length - 1;

while (low <= high && target >= this.arr[low] && target <= this.arr[high]) {
if (low === high) {
if (this.arr[low] === target) return low;
return -1;
}

const pos = Math.floor(
low + ((target - this.arr[low]) / (this.arr[high] - this.arr[low])) * (high - low)
);

if (this.arr[pos] === target) return pos;
if (this.arr[pos] < target) low = pos + 1;
else high = pos - 1;
}

return -1;
}
}
module.exports = InterpolationSearch;

0 comments on commit 5382dc1

Please sign in to comment.