用php读取并写以下内容$arr=[23,12,45,56,78,34,3,9]; 使用二分查找 查询56的下标
时间: 2023-09-30 12:09:01 浏览: 35
以下是PHP代码实现:
```php
$arr = [23, 12, 45, 56, 78, 34, 3, 9];
$target = 56;
// 定义二分查找函数
function binarySearch($arr, $target)
{
$left = 0;
$right = count($arr) - 1;
while ($left <= $right) {
$mid = floor(($left + $right) / 2);
if ($arr[$mid] == $target) {
return $mid;
} elseif ($arr[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return -1;
}
// 调用二分查找函数
$index = binarySearch($arr, $target);
if ($index == -1) {
echo "未找到目标元素";
} else {
echo "目标元素的下标为:" . $index;
}
```
输出结果为:
```
目标元素的下标为:3
```
说明在给定数组中,目标元素 56 的下标为 3。
相关问题
$arr=[23,12,45,56,78,34,3,9]; 使用二分查找 查询56的下标
二分查找是一种针对有序数组的搜索算法,可以快速定位指定元素在数组中的位置。以下是 PHP 实现二分查找的代码:
```php
function binary_search($arr, $target) {
$left = 0;
$right = count($arr) - 1;
while ($left <= $right) {
$mid = floor(($left + $right) / 2);
if ($arr[$mid] == $target) {
return $mid;
} elseif ($arr[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return -1; // 如果没找到,返回 -1
}
$arr = [23, 12, 45, 56, 78, 34, 3, 9];
$target = 56;
$index = binary_search($arr, $target);
echo "target index: " . $index; // 输出 "target index: 3"
```
所以,以上代码可以找到 56 的下标为 3。
用php$arr=[23,12,45,56,78,34,3,9]; 使用二分查找 查询56的下标
二分查找(Binary search)要求待查找的序列有序,每次查找都取中间位置的值与待查关键字进行比较,如果中间位置的值比待查找的关键字大,则在序列的左半部分继续执行查找;如果中间位置的值比待查找的关键字小,则在序列的右半部分继续执行查找,直到查找到关键字为止,或者序列中没有这样的关键字。
在 PHP 中可以使用内置函数 `array_search` 来实现二分查找。
以下是使用二分查找在给定数组中查找 56 的下标的 PHP 代码示例:
```php
<?php
$arr = [3, 9, 12, 23, 34, 45, 56, 78];
$index = array_search(56, $arr);
if ($index === false) {
echo "未找到";
} else {
echo "56 的下标为:" . $index;
}
?>
```
输出结果为:
```
56 的下标为:6
```