HomeAbout

Search

Linear Search

Looking at every element until finding the target:

const linearSearch = (list, item) => { for (const [i, element] of list.entries()) { if (element === item) { return i } } }

Big O would be O(n) because, at worst, we would need to search every element to check the presence of target value.

Binary Search

Binary search assumes the data structure you are performing the search is ordered.

Performing binary search on already sorted data structure would result in O(log n) complexity.

const binarySearch = (list, item) => { let low = 0 let high = list.length - 1 while (low <= high) { const mid = Math.floor((low + high) / 2) const guess = list[mid] if (guess === item) { return mid } if (guess > item) { high = mid - 1 } else { low = mid + 1 } } return null //if not found } console.log(binarySearch([1,2,3,4,5], 1)) //0 console.log(binarySearch([1,2,3,4,5], 5)) //4 console.log(binarySearch([1,2,3,4,5], 6)) //null
AboutContact