您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在PHP中进行二分查找

2024/3/24 17:55:36发布20次查看
什么是二分查找?二分搜索是一种搜索算法,用于有效地查找排序数组(或列表)中目标值的位置。它的工作原理是重复将搜索范围一分为二,并将中间元素与目标值进行比较。
二分查找算法遵循以下步骤:
从整个排序数组开始。
将左指针设置为数组的第一个元素,将右指针设置为最后一个元素。
计算中间索引作为左右指针的平均值(整数除法)。
将中间索引处的值与目标值进行比较。
如果中间值等于目标值,则搜索成功,算法返回索引。
如果目标值大于中间值,则通过将左指针更新为 mid + 1 来消除搜索范围的左半部分。
如果目标值小于中间值,则通过将右指针更新为 mid - 1 来消除搜索范围的右半部分。
重复步骤3到7,直到找到目标值或搜索范围为空(左指针大于右指针)。
如果搜索范围为空并且未找到目标值,则算法得出结论:目标值不存在于数组中并返回 -1 或适当的指示。
二分查找是一种非常高效的算法,时间复杂度为 o(log n),其中 n 是数组中元素的数量。它对于大型排序数组特别有效,因为它通过在每一步将搜索范围一分为二来快速缩小搜索范围,即使有大量元素也可以快速搜索。
二分查找的 php 程序方法 1 - 使用迭代示例<?phpfunction binarysearch($arr, $target) { $left = 0; $right = count($arr) - 1; while ($left <= $right) { $mid = floor(($left + $right) / 2); // check if the target value is found at the middle index if ($arr[$mid] === $target) { return $mid; } // if the target is greater, ignore the left half if ($arr[$mid] < $target) { $left = $mid + 1; } // if the target is smaller, ignore the right half else { $right = $mid - 1; } } // target value not found in the array return -1;}// example usage 1$sortedarray = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];$targetvalue = 91;$resultindex = binarysearch($sortedarray, $targetvalue);if ($resultindex === -1) { echo target value not found in the array.<br>;} else { echo target value found at index $resultindex.<br>;}// example usage 2$targetvalue = 42;$resultindex = binarysearch($sortedarray, $targetvalue);if ($resultindex === -1) { echo target value not found in the array.;} else { echo target value found at index $resultindex.;}?>
输出target value found at index 9.target value not found in the array.
方法 2 - 使用递归示例<?phpfunction binarysearchrecursive($arr, $target, $left, $right) { if ($left > $right) { // target value not found in the array return -1; } $mid = floor(($left + $right) / 2); // check if the target value is found at the middle index if ($arr[$mid] === $target) { return $mid; } // if the target is greater, search the right half if ($arr[$mid] < $target) { return binarysearchrecursive($arr, $target, $mid + 1, $right); } // if the target is smaller, search the left half return binarysearchrecursive($arr, $target, $left, $mid - 1);}// wrapper function for the recursive binary searchfunction binarysearch($arr, $target) { $left = 0; $right = count($arr) - 1; return binarysearchrecursive($arr, $target, $left, $right);}// example usage$sortedarray = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];$targetvalue = 16;$resultindex = binarysearch($sortedarray, $targetvalue);if ($resultindex === -1) { echo target value not found in the array.;} else { echo target value found at index $resultindex.;}?>
输出target value found at index 4.
结论总之,二分搜索是一种强大的算法,可以在排序数组中有效地查找目标值。它提供了两种常见的实现:迭代和递归。迭代方法使用 while 循环重复将搜索范围一分为二,直到找到目标值或范围变空。它具有简单的实现方式,非常适合大多数场景。另一方面,递归方法采用递归函数来执行二分搜索。它遵循与迭代方法相同的逻辑,但使用函数调用而不是循环。递归二分搜索提供了更简洁的实现,但由于函数调用堆栈操作可能具有稍高的开销。总的来说,这两种方法都提供了执行二分搜索操作的高效可靠的方法。
以上就是在php中进行二分查找的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product