二分查找算法是在有序数组中用到的较为频繁的一种算法,在未接触二分查找算法时,最通用的一种做法是,对数组进行遍历,跟每个元素进行比较,其时间为O(n).但二分查找算法则更优,因为其查找时间为O(lgn),譬如数组{1, 2, 3, 4, 5, 6, 7, 8, 9},查找元素6,用二分查找的算法执行的话,其顺序为:
1. 第一步查找中间元素,即5,由于5<6,则6必然在5之后的数组元素中,那么就在{6, 7, 8, 9}中查找,
2. 寻找{6, 7, 8, 9}的中位数,为7,7>6,则6应该在7左边的数组元素中,那么只剩下6,即找到了。
二分查找算法就是不断将数组进行对半分割,每次拿中间元素和goal进行比较。
C++实现(来自二分查找算法)
#include <iostream>
using namespace std;
int binary_search(int *a,int len,int goal);
int main()
{
const int LEN = 10;
int a[LEN];
for (int i = 0;i<LEN;i++)
a[i] = i*3;
int target = 5;
int index = binary_search(a,LEN,target);
if (index != -1)
cout<<target<<"在数组中的下标为"<<index<<endl;
else
cout<<"不存在"<<target<<endl;
system("pause");
return 0;
}
int binary_search(int *a,int len,int goal)
{
int low = 0;
int high = len-1;
while(low<=high)
{
int middle = (high -low)/2+low;
if(a[middle] == goal)
return middle;
else if(a[middle]>goal){
high = middle-1;
cout<<"high="<<high<<endl;
}
else if(a[middle]<goal){
low = middle+1;
cout<<"low="<<low<<endl;
}
}
return -1;
}
编译运行结果:
high=3 low=2 high=1 不存在5 请按任意键继续. . .
Python实现
def binary_search(lst,goal):
l = len(lst)
left = 0
right = l-1
while(left <= right):
middle = (right - left)/2+left
print middle
if lst[middle] == goal:
return middle
elif lst[middle]>goal:
right = middle -1
elif lst[middle]<goal:
left = middle +1
return -1
运行以下实例
length = 10
lst = []
for i in range(length):
lst.append(i*3)
goal = 21
index = binary_search(lst,goal)
if (index!=-1):
print 'the index of number %d is %d.'%(goal,index)
else:
print 'the number %d does not exist.'%(goal)
结果:
4
7
the index of number 21 is 7.