Interpolation Search in JavaScript


Interpolation Search

Interpolation search is an algorithm for searching for a key in an array that has been ordered by numerical values assigned to the keys (key values).

For example

Suppose, we have a sorted array of n uniformly distributed values arr[], and we need to write a function to search for a particular element target in the array.

It does the following operations to find the position −

// The idea of the formula is to return a higher value of pos

// when element to be searched is closer to arr[hi]. And

// smaller value when closer to arr[lo]

pos = lo + ((x - arr[lo]) * (hi - lo) / (arr[hi] - arr[Lo]))

Keys −

  • arr[] - Array where elements need to be searched

  • x - Element to be searched

  • lo - Starting index in arr[]

  • hi - Ending index in arr[]

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a search target as the second argument.

The function should make use of the Interpolation search algorithm to search for the target in the array.

Example

Following is the code −

const arr = [1, 4, 6, 7, 9, 12, 15, 16, 17, 23, 25, 26, 27, 31];
const target = 25;
const interpolationSearch = (arr = [], target) => {
   let left = 0;
   let right = arr.length - 1;
   while (left <= right) {
      const rangeDelta = arr[right] - arr[left];
      const indexDelta = right - left;
      const valueDelta = target - arr[left];
      if (valueDelta < 0) {
         return -1;
      }
      if (!rangeDelta) {
         return arr[left] === target ? left : -1;
      }
      const middleIndex = left + Math.floor((valueDelta * indexDelta) / rangeDelta);
      if (arr[middleIndex] === target) {
         return middleIndex;
      }
      if (arr[middleIndex] < target) {
         left = middleIndex + 1;
      } else {
         right = middleIndex - 1;
      }
   };
   return -1;
};
console.log(interpolationSearch(arr, target));

Output

Following is the output on console −

10

Updated on: 11-Dec-2020

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements