数据结构与算法 :C/PHP 二分查找实现

c语言实现:
//c语言实现二分搜索
#include 

int binarySearch(int *p, int size, int target)
{
    int left  = 0;
    int right = size - 1;
    int mid = (left + right)/2;
    while(left <= right){
        mid = (left + right)/2;
        if (p[mid] == target)
        {
            return mid;
        }else{
            if (p[mid] > target)
            {
                right = mid - 1;
            }else{
                left = left + 1;
            }
        }
    }
    return -1;
}

int main()
{
    int nums[12] = {0,1,2,3,4,5,6,7,8,9,100,200};
    int size   = sizeof(nums) / sizeof(nums[0]);
    int res = binarySearch(nums, size,100);
    printf("res:%d\n",res);
    return 0;
}
PHP实现:
//PHP二分搜索
//这里使用了PHP7的强类型语法
function index(array $nums, int $target): int
{
    $left = 0;
    $len  = count($nums);
    $right= $len - 1;
    $ans  = -1;
    while ( $left <= $right) {
        $mid = floor(($left + $right)/2);
        if ($target == $nums[$mid]) {
            return $mid;
        }elseif ($target > $nums[$mid]) {
            $left = $mid + 1;
        }else{
            $right = $mid - 1;
        }
    }
    return $ans;
}

你可能感兴趣的