Mathmagician Wiki
Advertisement

Note: this is broken, needs fixing

e.g. binarySearch([1, 2, 4, 4, 6, 7], 4)

  • Expected value: 2
  • Actual value: -1 (bug)

An implementation of binary search in JavaScript[]

/**
 * @param array a pre-sorted array of integers, strings or anything-that-can-be-compared-with <
 * @param value the value to search for
 * @return the index at which the value was found, or -1 if it wasn't found
 */
function binarySearch(array, value) {
	var left = -1, right = array.length, mid;
	while (right - left > 1) {
		mid = (right + left) >> 1;
		(array[mid] < value) ? left = mid : right = mid;
	}
	return (array[mid] === value) ? mid : -1;
}
Advertisement