二分搜索是一种在排序数组中查找元素的更有效的算法。它的工作原理是反复将搜索间隔分成两半。以下是二元搜索函数的详细分解:
function binarySearch(array $arr, float|int $x) { $low = 0; $high = count($arr)-1; // $midIndex = (int) ($low + ($high - $low)/2); $i = 0; while($low <= $high){ $i++; $midIndex = (int) ($low + (($high - $low)/2)); //the same as intdiv($low + $high, 2); if($arr[$midIndex] == $x){ return "The number {$x} was found in index {$midIndex} of the array. The number of iteration was {$i}"; }elseif($x > $arr[$midIndex]){ $low = $midIndex +1; echo $low."\n"; }else{ $high = $midIndex - 1; } } return "The number {$x} was not found in the array"; } echo binarySearch([1,2,3,4,5,6,7,8,9,10,44,45,46,47,48,49,50], 45)
函数binarySearch接受两个参数:
线性搜索是用于查找数组中特定元素的最简单的搜索算法之一。让我们分解一下 PHP 中的 LinearSearch 函数。
function linearSearch(array $arr, float|int $x) { for($i=0; $i < count($arr); $i++){ if($x === $arr[$i]){ return "The number {$x} was found in index {$i} of the array\n"; } } return "The number {$x} was not found in the array\n"; } echo linearSearch([1,5,6,3,4,11,3,2], 4);
函数 LinearSearch 接受两个参数:
以上是搜索算法的详细内容。更多信息请关注PHP中文网其他相关文章!