python实现二分查找算法
二分查找算法:简单的说,就是将一个数组先排序好,比如按照从小到大的顺序排列好,当给定一个数据,比如target,查找target在数组中的位置时,可以先找到数组中间的数array[middle]和target进行比较,当它比target小时,那么target一定是在数组的右边,反之,则target在数组的左边,比如它比target小,则下次就可以只比较[middle+1, end]的数,继续使用二分法,将它一分为二,直到找到target这个数返回或者数组全部遍历完成(target不在数组中)
优点:效率高,时间复杂度为O(logN);
缺点:数据要是有序的,顺序存储。
python的代码实现如下:
#!/usr/bin/python env # -*- coding:utf-8 -*- def half_search(array,target): low = 0 high = len(array) - 1 while low < high: mid = (low + high)/2 if array[mid] > target: high = mid - 1 elif array[mid] < target: low = mid + 1 elif array[mid] == target: print 'I find it! It is in the position of:',mid return mid else: print "please contact the coder!" return -1 if __name__ == "__main__": array = [1, 2, 2, 4, 4, 5]
运行结果如下:
I find it! It is in the position of: 4 4 -1 I find it! It is in the position of: 0 0 -1
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28