#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def binaray_search(list, item):
low = 0
high = len(list) - 1
i = 0
while(low <= high):
mid = (low + high)/2
guess = mid
if guess == item:
i= i + 1
print('got it!')
return guess,i
elif guess < item:
low = mid + 1
i= i + 1
else:
high = mid - 1
i= i + 1
return 'no match', i
if __name__ == '__main__':
my_list = [1,2,3,4,5,6,7,8,9,10, 11,12]
my_item = 13
a = binaray_search(my_list, my_item)[0]
i= binaray_search(my_list, my_item)[1]
print (i)
if a == 'no match':
print('no answer')
else:
print('to_fine_num is : %d, take %d times to find' %(a, i))
- 以上是python实现二分法搜索的代码,对于长度为2^n的list,最多需要n次即可确定目标,时间复杂度为O(logn).
- 前提:查找的list必须有序。