|
| 1 | +/** |
| 2 | + * @description - This function implements the interpolation search algorithm |
| 3 | + * @param {Array} arr - The array to be searched |
| 4 | + * @param {Number} x - The element to be searched |
| 5 | + * @returns {Number} - The index of the element if found, else -1 |
| 6 | + * @example |
| 7 | + * interpolationSearch([1, 2, 3, 4, 5], 3) // returns 2 |
| 8 | + * interpolationSearch([1, 2, 3, 4, 5], 6) // returns -1 |
| 9 | + * interpolationSearch([1, 2, 3, 4, 5], 1) // returns 0 |
| 10 | + * |
| 11 | + * ### Time Complexity |
| 12 | + * Best Case: O(1) |
| 13 | + * Average Case: O(log(log(n))) |
| 14 | + * Worst Case: O(n) |
| 15 | + * |
| 16 | + * ### Space Complexity |
| 17 | + * O(1) |
| 18 | + * |
| 19 | + ### Explanation of the algorithm |
| 20 | + * The interpolation search algorithm is an improvement over the binary search algorithm. |
| 21 | + * The interpolation search algorithm works on the probing position of the required value. |
| 22 | + * For this algorithm to work properly, the data collection should be in a sorted form and equally distributed. |
| 23 | + * The idea of formula is to return higher value of pos when element to be searched is closer to arr[hi]. And smaller value when closer to arr[lo] |
| 24 | + * |
| 25 | + * ### Pseudocode |
| 26 | + * 1. Find the position to be searched |
| 27 | + * 2. If it is a match, return the index of the item, and exit. |
| 28 | + * 3. If the item is less than arr[pos], calculate the probe position of the left sub-array. Otherwise calculate the same in the right sub-array. |
| 29 | + * 4. Repeat until a match is found or the sub-array reduces to zero. |
| 30 | + */ |
| 31 | + |
| 32 | +const interpolationSearch = (arr, x) => { |
| 33 | + let lo = 0; // lower bound |
| 34 | + let hi = arr.length - 1; // upper bound |
| 35 | + while (lo <= hi && x >= arr[lo] && x <= arr[hi]) { |
| 36 | + // check if x is in range of the array |
| 37 | + if (lo === hi) { |
| 38 | + // if lower bound is equal to upper bound |
| 39 | + if (arr[lo] === x) return lo; // if the element is found, return the index |
| 40 | + return -1; // else return -1 |
| 41 | + } |
| 42 | + let pos = |
| 43 | + lo + Math.floor(((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); // calculate the probe position |
| 44 | + if (arr[pos] === x) return pos; // if the element is found, return the index |
| 45 | + if (arr[pos] < x) |
| 46 | + lo = |
| 47 | + pos + |
| 48 | + 1; // if the element is less than the element at pos, update the lower bound |
| 49 | + else hi = pos - 1; // else update the upper bound |
| 50 | + } |
| 51 | + return -1; // if the element is not found, return -1 |
| 52 | +}; |
| 53 | + |
| 54 | +module.exports = interpolationSearch; |
| 55 | + |
| 56 | +console.log(interpolationSearch([1, 2, 3, 4, 5], 3)); // returns 2 |
| 57 | +console.log(interpolationSearch([1, 2, 3, 4, 5], 6)); // returns -1 |
| 58 | +console.log(interpolationSearch([1, 2, 3, 4, 5], 1)); // returns 0 |
0 commit comments