The premise of binary search algorithm:
1, for the index array;
2, for arrays that are already lined up.
Code Demo:
//function function: Find data from position $begin start to position $end in array $arr $sfunctionBinary_search ($arr,$s,$begin,$end){ $mid= Floor(($begin+$end)/2);//Locate the middle position $mid _value=$arr[$mid];//gets the value of the middle item if($mid _value==$s) { return true; }Else if($mid _value>$s) { if($begin>$mid-1)//if the starting position is larger than the end position, it means that it must not be found. { return false; } //the middle item is bigger than the $s to find, go to the left to find it: $re= Binary_search ($arr,$s,$begin,$mid-1); }Else { if($mid+1 >$end)//if the starting position is larger than the end position, it means that it must not be found. { return false; } //the middle item is smaller than the $s to be searched, go to the right to find it; $re= Binary_search ($arr,$s,$mid+1,$end); } return $re;}
test code:
<? php $a = array ( 1,3,11,18,19,22,25,33,34,38,44,55,56,58 $search = 35; // The number to find $len = count ( $a ); // number, natural, maximum subscript is len-1//use the Binary_search () function to find len-1 $search $v 1 = Binary_search ( $a , $search , 0, $len -1 echo "The result is:" var_dump ( $v 1 );
Test results:
· The result is: BOOL (false)
A little explanation of the efficiency (performance) problem of the binary lookup algorithm:
1000 data, about 10 times to find out;
100 complete data, about 20 times to find out;
1 billion data, about 30 times to find out;
4 billion data, about 32 times to find out.
Binary search algorithm