NetBeans PHP Tutorial – Binary Search #15

In this tutorial I show how to implement a binary search algorithm in PHP.

Code:

<?php
 
$binaryArray = generateOrderedArray();
 
print(binarySearch($binaryArray, 640));
 
function binarySearch($array, $searchFor) {
	$low = 0;
	$high = count($array) - 1;
	$mid = 0;
 
	while ($low <= $high) { // While the high pointer is greater or equal to the low pointer
		$mid = floor(($low + $high) / 2);
		$element = $array[$mid];
 
		if ($searchFor == $element) { // If this is the value we're searching for
			return $mid;
		} else if ($searchFor < $element) {
			$high = $mid - 1;
		} else {
			$low = $mid + 1;
		}
	}
	return -1;
}
 
function generateOrderedArray() {
	$array = [];
 
	for ($i = 0; $i <= 99; $i++) {
		$array[$i] = $i * 10;
	}
	return $array;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *