Tutorialspoint.dev

Binary Search in PHP

Binary Search is a searching technique used to search an element in a sorted array. In this article, we will learn about how to implement Binary Search in PHP using iterative and recursive way. Given a array of numbers, we need to search for the presence of element x in the array using Binary Search.

Examples:

Input : 1 2 3 4 5
        5 
Output : 5 Exists

Input : 1 5 8
        0
Output : 0 Doesnt Exist



This searching technique is more efficient than linear search.

Method 1(Iterative):

Steps Involved:
1) Sort the array as binary search only works on sorted ranges
2) Compute the middle element if the element we wish to search is greater than the middle element search on the right side else search on the left.
3) Return True if the element is found.

<?php
  
function binarySearch(Array $arr, $x)
{
    // check for empty array
    if (count($arr) === 0) return false;
    $low = 0;
    $high = count($arr) - 1;
      
    while ($low <= $high) {
          
        // compute middle index
        $mid = floor(($low + $high) / 2);
   
        // element found at mid
        if($arr[$mid] == $x) {
            return true;
        }
  
        if ($x < $arr[$mid]) {
            // search the left side of the array
            $high = $mid -1;
        }
        else {
            // search the right side of the array
            $low = $mid + 1;
        }
    }
      
    // If we reach here element x doesnt exist
    return false;
}
  
// Driver code
$arr = array(1, 2, 3, 4, 5);
$value = 5;
if(binarySearch($arr, $value) == true) {
    echo $value." Exists";
}
else {
    echo $value." Doesnt Exist";
}
?>

/div>

Output:

5 Exists

Method 2(Recursive):
Recursion is a way where we repeatedly call the same function until a base condition is matched to end the recursion.
Proceeding with the steps in method 1 here we use the same idea by just changing the parameters of the function in recursive manner and breaking down the problem.

function binarySearch(Array $arr, $start, $end, $x){
    if ($end < $start)
        return false;
   
    $mid = floor(($end + $start)/2);
    if ($arr[$mid] == $x
        return true;
  
    elseif ($arr[$mid] > $x) {
  
        // call binarySearch on [start, mid - 1]
        return binarySearch($arr, $start, $mid - 1, $x);
    }
    else {
  
        // call binarySearch on [mid + 1, end]
        return binarySearch($arr, $mid + 1, $end, $x);
    }
}
  
// Driver code
$arr = array(1, 2, 3, 4, 5);
$value = 5;
if(binarySearch($arr, 0, count($arr) - 1, $value) == true) {
    echo $value." Exists";
}
else {
    echo $value." Doesnt Exist";
}

Output:

5 Exists

Related PHP functions:

in_array() in PHP

array_key_exists() in PHP



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter