二分搜索

 1 from math import ceil, floor
 2 
 3 def b_search(source, target):
 4     max = len(source)
 5     mid = max/2
 6     if target>source[int(mid)]:
 7         mid = ceil(mid)
 8     else:
 9         mid = floor(mid)
10     target_sub = mid;
11 
12     if source[mid]>target:
13         target_sub = b_search(source[:mid], target)
14     elif source[mid]<target:
15         print(mid, max, source[mid:max])
16         target_sub = b_search(source[mid:max], target)
17 
18     return target_sub
19 
20 arr = list(range(20))
21 print(arr)
22 mid = b_search(arr, 15)
23 print(mid)

 

posted on 2013-05-05 16:34  mtima  阅读(138)  评论(0编辑  收藏  举报

导航