Skip to content

How to implement binary search

daisho edited this page Jul 23, 2020 · 1 revision

Ability to implement a binary search function on the fly seems to be fundamental if you want to call yourself a mid-level developer or above.

Note

If the array is not sorted, binary search doesn't work.

function binarySearch(list, item) {
	let min = 0;
	let max = list.length - 1;
	let guess;

	while (min <= max) {
		// sets `guess` to medial index of the list; any idex is fine though
		// if list.length is 7: (0+7)/2 => 3.5 => Math.floor => 3
		guess = Math.floor((min + max) / 2);

		if (list[guess] === item) {
			// this happens in the first iteration if you are lucky
			return guess;
		}
		else {
			if (list[guess] < item) {
				// if value of `guess` index is smaller than item
				// item shouldn't be left side of list because the list is supposed to be sorted
				min = guess + 1;
			}
			else {
				// if value of `guess` index is larger than item
				// item should be left side of list so move max to left by setting to `guess - 1`
				max = guess - 1;
			}
		}
	}
	// if the item can not be found in the list, returns `-1` like `array.prototype.indexOf()`
	return -1;
}

// in order to make it work, the list has to be sorted by order
// if not sort it first `[2, 10, 4, 12].sort((a, b) => a - b)`
console.log(binarySearch([2, 4, 10, 12], 12));
Clone this wiki locally