Please visit our sponsor
UNKNOWN //************************************** // Name: Binary search // Description: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. // By: Bhushan Paranjpe // // // Inputs:None // // Returns:None // //Assumes:None // //Side Effects:None //This code is copyrighted and has limited warranties. //Please see //for details. //************************************** <?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;} --&gt; if your objective is to return the index {return 1;} else {return 0;} //{return -1;} --&gt; if your objective is to return the index } ?&gt;