mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00

* 📦 NEW: Added solution for ProjectEuler-007 * 🐛 FIX: Spelling mistake fixes * 👌 IMPROVE: changed variable name from `inc` to `candidateValue` and thrown error in case of invalid input * 👌 IMPROVE: Modified the code * 👌 IMPROVE: Added test case for ProjectEuler Problem001 * 👌 IMPROVE: Added test cases for Project Euler Problem 4 * 👌 IMPROVE: auto prettier fixes --------- Co-authored-by: Omkarnath Parida <omkarnath.parida@yocket.in>
40 lines
920 B
JavaScript
40 lines
920 B
JavaScript
/**
|
|
* Interpolation Search
|
|
*
|
|
* Time Complexity:
|
|
* -Best case: O(1)
|
|
* -Worst case: O(n)
|
|
* -O((log(log(n))) If the data are uniformly distributed
|
|
*
|
|
*
|
|
*/
|
|
|
|
export function interpolationSearch(arr, key) {
|
|
const length = arr.length - 1
|
|
let low = 0
|
|
let high = length
|
|
let position = -1
|
|
let delta = -1
|
|
|
|
// Because the array is sorted the key must be between low and high
|
|
while (low <= high && key >= arr[low] && key <= arr[high]) {
|
|
delta = (key - arr[low]) / (arr[high] - arr[low])
|
|
position = low + Math.floor((high - low) * delta)
|
|
|
|
// Target found return its position
|
|
if (arr[position] === key) {
|
|
return position
|
|
}
|
|
|
|
// If the key is larger then it is in the upper part of the array
|
|
if (arr[position] < key) {
|
|
low = position + 1
|
|
// If the key is smaller then it is in the lower part of the array
|
|
} else {
|
|
high = position - 1
|
|
}
|
|
}
|
|
|
|
return -1
|
|
}
|