Binary search algorithm

Binary search algorithm

Binary search algorithm function. Takes an array as an argument and the element to be searched for in the array. Returns ‘1′ if found, ‘0′ if not. The code can be modified slightly to return the array index of the found element.

<?php
function BinarySearch($ArrayToSearch/*array to search through*/, $SearchFor/*element to search for*/)
{
sort($ArrayToSearch);//must sort the array

//index
$first=0;
$last=count($ArrayToSearch)-1;
$mid=($first+$last)/2;
$SearchFor=strval(trim($SearchFor));
while
(
($first<=$last)&&
(strval(trim($ArrayToSearch[$mid]))!=$SearchFor)
)
{
if(strcmp(strtolower($SearchFor),strtolower($ArrayToSearch[$mid]))<0)
{$last=$mid-1;}//search the upper half
else
if(strcmp(strtolower($SearchFor),strtolower($ArrayToSearch[$mid]))>0)
{$first=$mid+1;}//search the lower half

$mid=($first+$last)/2;//new mid point
}

if(strval(trim($ArrayToSearch[$mid]))==$SearchFor)
//{return $mid;} –> if your objectiv
// e is to return the index
{return 1;}
else
{return 0;}
//{return -1;} –> if your objective
// is to return the index
}
?>

Leave a Reply


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.