Binary Search

Jaskomal
2 min readAug 8, 2021

Binary Search is used on sorted data to quickly find the value you are looking for in 0(log n) time. This is a time saver versus the linear way of looking through each value one at time which leads to a run time of 0(n).

A real world example to help conceptualize this would be searching for the word xylophone in a dictionary. Now you wouldn’t start at the beginning of the dictionary with the letter A that would take you forever. Instead you would go close to the end knowing x is close to the last letter in the alphabet. If you opened to a page with words with the letter w you would go forward whereas if you opened to a page with words starting with z you would go backwards. This looking forward or backwards is essentially the function of binary search.

A key step when thinking of binary search is to find the middle of the current list. To do this set the first value as the left value and the last value as the right value and divide by 2. This way the middle value will always be the midpoint of the list.

const bSearch = (arr, target) => {let left = 0;let right = arr.length;while (right > left) {const index = Math.floor((left + right) / 2);const checking = arr[index];console.log(`index equals: ${index}`)if (checking === target) {return index;} else if (target > checking) {left = index + 1;} else {right = index;}}return null;}const search = [1, 2, 7, 8, 22, 28, 41, 58, 67, 71, 94];const target = 2;const targetIndex = binarySearch(search, target);

--

--