给定的数组具有重复的元素,因此,基本上,我想找到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。有什么建议?
我没有看到您的循环,但我认为使用它真的很容易获得这种功能
$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
like一起使用
$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
asort($arr);
echo array_search(4,$arr);//6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句