c 语言实现:
// c 语言实现二分搜寻
#include <stdio.h>
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;
}