Binary Search in PHP

Description: Typical binary search done through PHP. It takes an array of values which have a numerical index (not an associative array), a value to search for and the minimum and maximum array index. It returns the index of the value found or -1 if the value was not found.
Tested Platform: PHP 5
Language: PHP
// Takes a non associative array and returns the index of the found value.
// Otherwise it returns -1. MinIndex and MaxIndex are the lowest and highest
// indexes of the array.

function BinarySearch($arNums, $searchValue, $minIndex, $maxIndex) {
	while ($maxIndex >= $minIndex) {
		$midpoint = (int)(($maxIndex - $minIndex) / 2) + $minIndex;
		
		if ($searchValue < $arNums[$midpoint]) { $maxIndex = $midpoint - 1; }
		else if ($searchValue > $arNums[$midpoint]) { $minIndex = $midpoint + 1; }
		else { return $midpoint; }
	}
	return -1;
}

Submitted: February 14, 2013

Return to the snippets listing