FANDOM


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 JavaScriptEdit

/**
 * @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;
}

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.