Home >Backend Development >PHP Tutorial >PHP binary search-recursive and non-recursive sample code sharing

PHP binary search-recursive and non-recursive sample code sharing

黄舟
黄舟Original
2017-03-18 09:52:341215browse

PHP Binary Search - Recursive and non-recursive sample code sharing

<?php
function binarySearch($arr, $val)
{
	$len = count($arr);
	if(!is_array($arr) || $len <= 0){
		return false;
	}
	
	if($val < $arr[0] || $val > $arr[$len-1]){
		return false;
	}
	
	$start = 0;
	$end = $len - 1;
	while($start <= $end){
		$mid = intval(( $end+$start )/2); //中间值
		if($arr[$mid] == $val){
			return $mid;
		}
		
		if($val < $arr[$mid]){
			$end = $mid - 1;
		}else{
			$start = $mid + 1;
		}
	}
	return false;
}

RecursiveImplementation:

<?php
// 递归
function binarySearch_r($arr, $low, $high, $key)
{
	$len = count($arr);
	if(!is_array($arr) || $len <= 0){
		return false;
	}
	
	if($key < $arr[0] || $key > $arr[$len-1]){
		return false;
	}
	
	if($low <= $high){
		$mid = intval( ($low+$high)/2 );
		if($arr[$mid] == $key){
			return true;
		}
		
		$func_name = FUNCTION;
		if($key < $arr[$mid]){
			return $func_name($arr, $low, $mid-1, $key);
		}
		else{
			return $func_name($arr, $mid+1, $high, $key);
		}
	}
	return false;
}

The above is the detailed content of PHP binary search-recursive and non-recursive sample code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn