In this case, what is wrong with binary search? & lt; php & nbsp; function & nbsp; binarySearch ($ arr, $ a) {& nbsp; & nbsp; $ low & nbsp; = & nbsp; 0; & nbsp; & what is wrong with binary search?
Function binarySearch ($ arr, $ ){
$ Low = 0;
$ High = count ($ arr)-1;
$ Mid = ceil ($ low + $ high)/2 );
While ($ low <= $ high ){
If ($ a ==$ arr [$ mid]) {
Echo "the location of the number to be searched is". "$ mid ";
}
If ($ a> $ arr [$ mid]) {
$ High = count ($ arr)-1;
$ Low = $ mid + 1;
$ Mid = ceil ($ low + $ high)/2 );
}
If ($ a <$ arr [$ mid]) {
$ Low = 0;
$ High = $ mid-1;
$ Mid = ceil ($ low + $ high)/2 );
}
}
}
$ Arr1 = array (5, 7, 9, 10, 12, 16, 19 );
BinarySearch ($ arr1, 12 );
?>
------ Solution --------------------
At the end of this post, xuzuning edited function binarySearch ($ arr, $ ){
$ Low = 0;
$ High = count ($ arr)-1;
$ Mid = ceil ($ low + $ high)/2 );
$ N = 0; measures to prevent endless loops
While ($ low <= $ high & $ n ++ If ($ a ==$ arr [$ mid]) {
Echo "the location of the number to be searched is". "$ mid ";
Break;
}
If ($ a> $ arr [$ mid]) {
$ High = count ($ arr)-1;
$ Low = $ mid-1; // pay attention to this
$ Mid = ceil ($ low + $ high)/2 );
}
If ($ a <$ arr [$ mid]) {
$ Low = 0;
$ High = $ mid + 1; // pay attention to this
$ Mid = ceil ($ low + $ high)/2 );
}
}
}
------ Solution --------------------
Write by php
Function binarySearch ($ arr, $ ){
$ Low = 0;
$ High = count ($ arr)-1;
$ Mid = ceil ($ low + $ high)/2 );
$ Num = count ($ arr );
While ($ low <= $ high & $ num --){
If ($ a ==$ arr [$ mid]) {
Echo "the location of the number to be searched is". "$ mid ";
Break;
}
List ($ low, $ high) = $ a> $ arr [$ mid]? Array ($ mid, $ high): array ($ low, $ mid );
$ Mid = ceil ($ low + $ high)/2 );
}
}
------ Solution --------------------