Parse the php dichotomy to see if the array contains an element

  • 2020-06-01 09:18:57
  • OfStack

2 division method to find whether the array contains a certain element, compatible with positive and negative order, the code implementation:

<?php

 $searchValue = (int)$_GET['key'];

 function search(array $array, $value)
 {
     $max = count($array)-1;
     $min = 0;
     $isAscSort = $array[$min] < $array[$max];

     while (TRUE) {
         $sum = $min+$max;
         $midKey = (int)($sum%2 == 1 ? ceil($sum/2) : $sum/2);

         if ($max < $min) {
             return -1;
         } else if ($value == $array[$midKey]) {
             return 1;
         } else if ($value > $array[$midKey]) {
             $isAscSort ? $min = $midKey+1 : $max = $midKey-1;
         } else if ($value < $array[$midKey]) {
             $isAscSort ? $max = $midKey-1 : $min = $midKey+1;
         }
     }
 }

 $array = array(
     '4', '5', '7', '8', '9', '10', '11', '12'
 );
 //  Positive sequence 
 echo search($array, $searchValue);

 //  The reverse 
 rsort($array);
 echo search($array, $searchValue);

I have searched this before. I have seen the example of baidu encyclopedia (the implementation of Java), as well as the Code written by some other technical curtains.all of them have problems and have not been realized at all.
This is an array that doesn't take into account the non-sequential keys, but it's mostly methods, and you can expand it yourself if you want.

Related articles: