- 实现一个有序数组的二分查找算法
- 实现模糊二分查找算法(比如大于等于给定值的第一个元素)
实现一个有效数组的二分查找算法
#include <stdio.h>
int binary_search(int arr[],int key,int sz)
{
int mid = 0;
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] < key)
left = arr[mid] + 1;
else if (arr[mid] > key)
right = arr[mid] - 1;
else
return mid;
}
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sz = sizeof(arr) / sizeof(arr[0]);
int key = 7;
int ret = binary_search(arr, key, sz);
if (ret == -1)
printf("找不到!
");
else
printf("找到了!下标为:%d
", ret);
return 0;
}
实现模糊二分查找算法(比如大于等于给定值的第一个元素)
class Solution(object):
def mySqrt(self, x):
if x==1 or x==0:
return x
else:
left=0
right=x
while left<right:
temp=(left+right)/2
if int(temp)**2<=x and int((temp+1))**2>=x:
if int((temp+1))**2==x:
temp=int((temp+1))
return(int(temp))
break
elif int(temp)**2<x and int(temp+1)**2<x:
left=temp
else:
right=temp