Binary Search in PHP

Binary Search is a searching technique used to search for an item in a sorted array. Here $data_array is a sorted array of items, and $search_item is the item we are looking at in the $data_array. Also, we need to pass the start and end index of the $data_array with the function call.

$data_array = [1,3,6,8,10,18,22,23,30,35,37,40,51,53,58,60,67,71,73,89,99];
$search_item = 8;
$start = 0;
$end = count($data_array) - 1;
	
function binary_search( $data_array, $search_item, $start, $end ){
	
	while($start <= $end){
		$mid = floor( ( $start + $end ) / 2 );
		if( $search_item < $data_array[$mid] ){
			$end = $mid - 1;
		}elseif( $search_item > $data_array[$mid] ){
			$start = $mid + 1;;
		}else{
			return $mid;
		}
	}
	return -1;
}

$itm_indx = binary_search( $data_array, $search_item, $start, $end ); 
if( $itm_indx < 0 ){
	echo 'item not found';
}else{
	echo 'item found in index = '.$itm_indx;
}

Leave a Reply

Your email address will not be published. Required fields are marked *