PHP 指数搜索(Exponential Search)

PHP程序展示了如何使用指数搜索在已排序数组中查找元素,通过递归二分查找法,时间复杂度为O(Logn)。文章讨论了其在不同搜索场景中的适用性。

 

        该搜索算法的名称可能会产生误导,因为它的工作时间为 O(Log n)。该名称来自于它搜索元素的方式。 

给定一个已排序的数组和要
搜索的元素 x,找到 x 在数组中的位置。

输入:arr[] = {10, 20, 40, 45, 55} 
        x = 45
输出:在索引 3 处找到元素

输入:arr[] = {10, 15, 25, 45, 55} 
        x = 15
输出:元素在索引 1 处找到

我们已经讨论过,线性搜索、二分搜索这个问题。
指数搜索涉及两个步骤:  
        1、查找元素存在的范围
        2、在上面找到的范围内进行二分查找。
如何找到元素可能存在的范围? 
        这个想法是从子数组大小 1 开始,将其最后一个元素与 x 进行比较,然后尝试大小 2,然后是 4,依此类推,直到子数组的最后一个元素不大于。 
        一旦我们找到一个索引 i(在重复将 i 加倍之后),我们就知道该元素必须存在于 i/2 和 i 之间(为什么是 i/2?因为我们在之前的迭代中找不到更大的值)下面给出的是上述步骤的实施。 

示例: 

<?php
// PHP program to find an element x in a
// sorted array using Exponential search.
 
// Returns position of first 
// occurrence of x in array
function exponentialSearch($arr, $n, $x)
{
     
    // If x is present at 
    // first location itself
    if ($arr[0] == $x)
        return 0;
 
    // Find range for binary search
    // by repeated doubling
    $i = 1;
    while ($i< $n and $arr[$i] <=$x)
        $i = $i * 2;
 
    // Call binary search 
    // for the found range.
    return binarySearch($arr, $i / 2, 
                        min($i, $n - 1), $x);
}
 
// A recursive binary search
// function. It returns location
// of x in given array arr[l..r] is
// present, otherwise -1
function binarySearch($arr, $l, 
                      $r, $x)
{
    if ($r >= $l)
    {
        $mid = $l + ($r - $l)/2;
 
        // If the element is
        // present at the middle
        // itself
        if ($arr[$mid] == $x)
            return $mid;
 
        // If element is smaller
        // than mid, then it
        // can only be present 
        // n left subarray
        if ($arr[$mid] > $x)
            return binarySearch($arr, $l, 
                                $mid - 1, $x);
 
        // Else the element 
        // can only be present
        // in right subarray
        return binarySearch($arr, $mid + 1,
                                    $r, $x);
    }
 
    // We reach here when
    // element is not present
    // in array
    return -1;
}
 
// Driver code
$arr = array(2, 3, 4, 10, 40);
$n = count($arr);
$x = 10;
$result = exponentialSearch($arr, $n, $x);
if($result == -1)
    echo "Element is not present in array";
else
    echo "Element is present at index ",
                                $result;
 
// This code is contributed by anuj_67
?> 

输出
元素出现在索引 3 处
时间复杂度: O(Log n) 
辅助空间:上述二分查找的实现是递归的,需要 O(Log n) 空间。通过迭代二分搜索,我们只需要 O(1) 空间。
指数搜索的应用: 
        1、指数二分搜索对于数组大小无限的无界搜索特别有用。请参阅无界二分搜索示例。
        2、对于有界数组,以及当要搜索的元素更接近第一个元素时,它比二分搜索效果更好。  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hefeng_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值