Binary Search in PHP | Explained with Code Examples

Write a program to implement binary search in PHP.

Given a sorted array, write a PHP code to search an element using binary search algorithm.

For example –

Input : { 1,  3,  5,  6,  7,  8,  9} ,  k = 6

Output: 3 (6 is found at 3rd index)

Before writing php code, let’s understand what is binary search.

Binary Search

In binary search, first we compute mid by using start and end index. In next step, we compare the value present at mid index to the value k. If search value is found, then the index of the middle element is returned else the algorithm repeats if the value is less than or greater than the middle element.

If the search value is less than or greater than the middle element, than the search continues in the lower or upper half of the array.

The time complexity of binary search is O(logn).

Important points regarding binary search

i)  Binary search works only with sorted array.
ii) The time complexity of a binary search is O(logn).

How to reverse a number in PHP

Binary Search in PHP

Binary Search in PHP – Code

We have discussed the binary search and it’s algorithm. Let’s write a php code to search an element in an array using binary search.

In this example, I have created one binarySearch method which accepts array and element to be searched in an array. The function return index if the value is found else it return -1.

Programming video tutorials

Binary search iterative and recursive algorithm video tutorial

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.