概念
二分查找只对有序数组有效,他是通过将数组一分为二,然后根据中心点与目标的大小比较排除掉另一半,到最后就能找到目标了
伪代码
binary_search:
left <- 0
right <- n-1
while left <= right then
mid <- left+(right-left)//2
if arr[mid] < target then
left = mid + 1
else if arr[mid] > target then
right = mid - 1
else
return mid
return -1
时间复杂度是 O(logn)
代码实现
C
#include <stdio.h>
static int binary_search(int arr[], size_t n, int target)
{
size_t left = 0, right = n - 1;
size_t mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (arr[mid] < target)
left = mid + 1;
else if (arr[mid] > target)
right = mid - 1;
else
return mid;
}
return -1;
}
static void print(int arr[], size_t size)
{
for (size_t i = 0; i < size; i++)
printf(" %d", arr[i]);
printf("\n");
}
int main(void)
{
int arr[] = {-1, 2, 3, 4, 6, 7, 9};
size_t size = sizeof(arr) / sizeof(arr[0]);
print(arr, size);
printf("target: %d\nindex: %d\n", 6, binary_search(arr, size, 6));
printf("target: %d\nindex: %d\n", 5, binary_search(arr, size, 5));
return 0;
}
Lua
local function binary_search(arr, target)
local left, right = 1, #arr
local mid
while left <= right do
mid = left + math.floor((right - left) / 2)
if arr[mid] < target then
left = mid + 1
elseif arr[mid] > target then
right = mid - 1
else
return mid
end
end
return -1
end
local function run()
local arr = {-1, 2, 3, 4, 6, 7, 9};
for _, v in ipairs(arr) do
io.write(" " .. tostring(v))
end
io.write("\n")
print(string.format("target: %d\nindex: %d", 4, binary_search(arr, 4)))
print(string.format("target: %d\nindex: %d", -2, binary_search(arr, -2)))
end
run()
posted on
浙公网安备 33010602011771号