Home > Backend Development > PHP Tutorial > PHP simple array search algorithm sharing

PHP simple array search algorithm sharing

小云云
Release: 2023-03-21 20:02:02
Original
1475 people have browsed it

Searching for arrays in PHP can use sequential search or binary search. Among them, sequential search is relatively simple, which is to compare and search one by one. But the disadvantage is also obvious. If the element being searched happens to be at the last one, the number of loops will be too many.

1. Sequential search algorithm description

Search the array one by one to confirm whether there is an element, and return the element if it exists location information. Flag information can be set, the initial value is false. Find the direct output location and set the flag to true. If the loop end flag is still false, it was not found.

Code reflection:

<br/>
Copy after login
$arr =[123,19,38,29,10,34];
function search($arr,$target){
    // 参数:目标数组 目标元素
	foreach ($arr as $key => $value) {
		if($value == $target){
			return $key.&#39;<br>&#39;;
		}
	}
	return false;
}
Copy after login

2. Binary search algorithm description<br/>

Assume that the array is in strict ascending order. If the target element is larger than the middle value, the search range is reduced by half to the right. If the value of the target element is smaller than the value of the middle element, the search range is reduced by half to the left.

Code reflection:

function half_search($arr,$target){
	// 定义出初始的第一个,最后一个元素的下标范围
	$len = count($arr);
	$left =0;
	$right =$len -1;
	// 循环查找
	// 范围不断的移动 ,必须满足一个条件
	// 最左侧元素的下标 小于等于右侧元素的下标
	while($left <= $right){
	 	// 中间元素的下标
	 	$middle = floor(($left + $right) /2);
	 	// 目标元素与中间元素进行比较
	 	if($target == $arr[$middle]){
	 		return $middle;
	 	}
	 	// 如果目标元素小于中间元素
	 	// 范围向左缩小一半	
	 	if($target < $arr[$middle]){
	 		$right =$middle-1 ;
	 	}
	 	// 如果目标元素大于中间元素
	 	// 范围向右缩小一半
	 	if($target > $arr[$middle]){
	 		$left = $middle + 1;
	 	}
	}
	 // 循环终止了
	 // 没有找到
	 return false;
}
Copy after login

Related recommendations:

PHP binary method to implement array search function tutorial

##php array Find key functions

php array search function summary

The above is the detailed content of PHP simple array search algorithm sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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