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

黄舟
Release: 2023-03-06 18:08:01
Original
1212 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template