Home Tutorial Php Phparray php array binary search

 
 

php array binary search
Posted on: October 28, 2009 at 12:00 AM
This section demonstrates how to use the binary search Array in the php

  • PHP Binary Search Array is used to search the given value in the array.
  • In php there is no function for the binary search like java or other language.
  • User can implement and use the binary search in php as given below

<?php

     $ar=array(10,20,30,40,40,60,65,89,74,36,48); 

     $size=sizeof($ar);

     $val=65;

     function binarySearch($value,$first,$last) {

         if($last<$first)   {

              return -1;

              }

          $mid=intVal(($first+$last)/2);

          global $ar;

          $a=$ar[$mid];

          if($a===$value)  {

              return $mid;

         }

          else {

              if($a>$value) {

               $last=$mid-1;

                  }

         else {

              if($a<$value) {

              $first=$mid+1;

                      }

                  }

         }

       return binarySearch($value,$first,$last);

     }

     foreach ($ar as $a)

     echo " ".$a;

     $y=binarySearch(intval($val),0,sizeof($ar)-1);

     if($y>=0)  {

     echo "<br>".$val." is present at ".$y." position in the given array";

        }

     else  {

     echo "<br>".$val ." is not prsesnt in the given array ";

     }

?>

Related Tags for php array binary search:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.