How to find out whether an ordered array contains a value in PHP (binary search)

Time:2020-4-6

Problem: for an ordered array, how to judge whether a given value exists in the array.

 

Idea: the simplest way to judge whether there is an array is to directly loop the array and compare each value. But for an ordered array, this writing does not make good use of the “ordered” feature.

So we use dichotomy to find,

//The ordered array is
$arr = array(2,5,66,87,954,1452,5865);
// lookup value
$str = 1452;
//Let's define three parameters first
$front = 0; // a start value subscript
$end = ($ARR) - 1; // an end value subscript
$mid = ($front + $end) / 2); // middle value subscript

1. For the first comparison, we can directly determine whether the search value STR is equal to the middle value mid, and if it is equal to it, return true directly;

2. If the search value STR is greater than the middle value mid, it means that the search value STR may be on the right side of the middle value. That is to say, the start value front needs to be re assigned = middle value mid + 1, and the end value end does not need to be changed. The middle value mid in turn is the new start value + end value;

3. If the search value STR is less than the middle value mid, it means that the search value STR may be on the left of the middle value, that is, the start value does not need to be changed, and the end value end needs to be re assigned = middle value – 1, and the middle value mid in turn is the start value + new end value;

—–As above, compare the incoming start value, end value and intermediate value. Once the start value is greater than the end value, it means that it is not found and the query is ended. Otherwise, it will return found.

 

The specific code is as follows:

$STR = 89; // find value
$arr = [1,55,66,89420]; // ordered array
$ren = find($arr, $str);

echo '';
($ren);

function find($arr, $str){
    $front = 0; // start subscript
    $end = ($ARR) - 1; // end subscript
    While ($front < = $end) {// end value is greater than start value, otherwise exit
        $mid = ($front + $end) / 2); // middle value subscript
        if($str == $arr[$mid]){
            Return $mid; // there is a subscript for the direct return value
        }
        if($str > $arr[$mid]){
            $front = $mid + 1; // in front
        }
        if($str < $arr[$mid]){
            $end = $mid - 1; // after
        }
    }
    return false;
}

Return result: 89 is the fourth element value subscript 3