二分搜尋是一種在排序數組中尋找元素的更有效的演算法。它的工作原理是反覆將搜尋間隔分成兩半。以下是二元搜尋函數的詳細分解:
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中文網其他相關文章!