使用二进制搜索PHP查找数组中最后一次出现元素的索引

时间:2015-09-15 05:27:15

标签: php arrays binary-search

给定的数组有重复的元素,所以基本上,我想找到我搜索过的元素最后一次出现的index

$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
$x = 4; // number to search
$low = 0;
$high = count($arr)-1;
// I want this function to return 6 which is the index of the last occurrence of 4, but instead I'm getting -1 .
function binary_search_last_occ($arr, $x, $low, $high)
{
    while ($low <=$high)
    {
        $mid = floor(($low+$high)/2);
        $result = -1;
        if ($arr[$mid] == $x)
        {
            // we want to find last occurrence, so go for
            // elements on the right side of the mid 
            $result = $mid;
            $low = $mid+1;
        }
        else if($arr[$mid] > $x)
        {
            $high = $mid-1;
        }
        else
            $low = $mid+1;
    } 
    return $result;  
}
echo binary_search_last_occ($arr, $x, $low, $high); // outputs -1 ? 

我不确定,为什么我得到-1。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

我没有看到你的循环,但我认为这很难用来获得这样的功能

$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
$result = [];
foreach($arr as $key => $val){
    $result[$val][] = $key;
}

echo end($result[4]);//6

或者您可以简单地使用asort功能和array_search一样使用

$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
asort($arr);
echo array_search(4,$arr);//6

答案 1 :(得分:2)

首先,对于二进制搜索,您的数组必须进行排序,如果您的数组未排序,您可以使用简单的方法,如

function binary_search_last_occ($arr, $x, $low, $high)
{
    $last_occ = -1;
    while ($low <=$high)
    {
         if($arr[$low] == $x)
            $last_occ = $low;
         $low++;
    }
    return $last_occ ;  
}

答案 2 :(得分:1)

并在while()上面定义$result以避免每次使用-1覆盖。因此,您将结果显示为-1。

$result = -1;

while ($low <=$high)
{
    $mid = floor(($low+$high)/2);

    if ($arr[$mid] == $x)
    {
        // we want to find last occurrence, so go for
        // elements on the right side of the mid 
        $result = $mid;
        $low = $mid+1;
    }
    else if($arr[$mid] > $x)
    {
        $high = $mid-1;
    }
    else
        $low = $mid+1;
} 
return $result;