Home

Search Algorithms

Search algorithms find the index of a specific value in an array. If the value is not found, they return -1.

Linear search goes through each element and checks to see if it’s the value.

function linearSearch(arr, value){
  for(let i = 0; i < arr.length; i++){
    if(arr[i] === value) return i
  }
  return -1
}

Binary search splits the search space in half depending if the middle of the array is less than or grater than the value. This repeats until the middle equals the value.

function binarySearch(arr, value){
  let left = 0
  let right = arr.length - 1

  while(left <= right){
    const mid = Math.floor((left + right) / 2)
    const midValue = arr[mid]

    if(midValue === value) return mid

    if(midValue < value){
      left = mid + 1
    }else{
      right = mid - 1
    }
  }
  return -1
}

Interpolation search is binary search, but instead of checking the center it makes an educated guess(probe) where the value would be in the input.

This best guess(probe) is gotten by using linear interpolation.

Linear interpolation is best used for uniformly distributed inputs.

function interpolationSearch(arr, value){
  let left = 0
  let right = arr.length - 1

  while(left <= right){
    const y1 = left, x1 = arr[left]
    const y2 = right, x2 = arr[right]
    const m = (y1 - y2)/(x1 - x2)
    const probeIndex = y1 + m * (value - x1)
    const probeValue = arr[probeIndex]

    if(probeValue === value) return probeIndex

    if(probeValue < value){
      left = probeIndex + 1
    }else{
      right = probeIndex - 1
    }
  }
  return -1
}