算法-在数组中获取制定值的索引值-php(二分法)

算法-在数组中获取制定值的索引值-php(二分法)

<?php


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param nums int整型一维数组 
 * @param target int整型 
 * @return int整型
 */
function search( $nums ,  $target )
{
    // write code here
    if (count($nums) == 0) {
        return -1;
    }
    $leftIndex = 0;
    $rightIndex = count($nums) - 1;
    // 只要下标一直是左边<=右边,就需要一直找
    while ($leftIndex <= $rightIndex){
        // 中间元素的索引
        $midIndex = floor(($leftIndex + $rightIndex) / 2);
        // 如果中间索引对应的值等于目标值
        if ($nums[$midIndex] == $target) {
            return $midIndex;
        }
        // 比较找到的值和目标值
        if ($nums[$midIndex] > $target) {
            $rightIndex = $midIndex - 1;
        } else {
            $leftIndex = $midIndex + 1;
        }
    }
    return -1;
}
posted @ 2025-01-12 21:19  alisleepy  阅读(15)  评论(0)    收藏  举报