Binary search PHP implementation
- /** Binary search: searches for the position of a value in the array.
- * @ $ Arr: array of operations, provided that they are arranged in order
- * @ $ Val: the value to be searched.
- * @ $ Low: the start position of the query. the default value is the first number of arrays.
- * @ Hight: the end position of the query.
- **/
- Function binarySearch ($ arr, $ val, $ hight, $ low = 0 ){
- While ($ low <= $ hight ){
- $ Mid = ceil ($ low + ($ hight-$ low)/2 );
- If ($ arr [$ mid] ==$ val ){
- Return $ mid;
- } Elseif ($ arr [$ mid]> $ val ){
- $ Hight = $ mid-1;
- } Else {
- $ Low = $ mid + 1;
- }
- }
- Return-1;
- }
- Header ('content-Type: text/html; charset = utf-8 ');
- // Generate an array
- $ Arr = range (0, 20 );
- Echo'
'; - print_r($arr);
- echo '
';
- $ Low = 0;
- $ Hight = count ($ arr)-1;
- $ FindVal = rand (0, 20 );
- $ Index = binarySearch ($ arr, $ findVal, $ hight, $ low );
- Printf ("The subscript '% s' of the searched value' % d' in the array", $ findVal, $ index );
- ?>
|
PHP