Why is it wrong to write binary search?
$ 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);?>
Reply to discussion (solution)
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 );
}
}
}
Write by php
Function binarySearch ($ arr, $ a) {$ 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 of queries is ". "$ mid"; break;} list ($ low, $ high) = $ a> $ arr [$ mid]? Array ($ mid, $ high): array ($ low, $ mid); $ mid = ceil ($ low + $ high)/2 );}}
This post was last edited by xuzuning at 17:42:33
Function binarySearch ($ arr, $ ){
$ Low = 0;
$ High = count ($ arr)-1;
$ Mid = ceil ($ low + $ high)/2 );
$ N = 0; measures to prevent endless loops ......
I'm a little dizzy. if it's four numbers, for example, $ r = array (1, 2, 3, 4) search for 1 doesn't seem to work with floor for $ mid. I understand that, it seems a bit problematic to use ceil ,,,,
Write by php
PHP code? 1234567891011121314 function binarySearch ($ arr, $ a) {$ low = 0; $ high = count ($ arr)-1; $ mid = ceil ($ low + $ high) /2); $ num = count ($ arr); while ($ low <= $ high &&...... [/Quote
Thanks to the moderator ,,,
Function binarySearch ($ arr, $ a) {$ low = 0; $ high = count ($ arr)-1; $ mid = ceil ($ low + $ high) /2); $ loop = count ($ arr); while ($ low <$ high-1 & $ loop --) {if ($ a = $ arr [$ mid]) {echo "the location of the number of queries is ". "$ mid"; return $ mid;} list ($ low, $ high) = $ a> $ arr [$ mid]? Array ($ mid, $ high): array ($ low, $ mid); $ mid = ceil ($ low + $ high)/2 );} echo "the number of queries is located between {$ low} and {$ high}" ;}$ arr1 = array (5, 7, 9, 10, 12, 16, 19 ); binarySearch ($ arr1, 11 );