We can describe it like this:  In computer science, a binary search is an algorithm for locating the position of an item in a sorted array. 

The idea is simple: compare the target to the middle item in the list. If the target is the same as the middle item, you've found the target. If it's before the middle item, repeat this procedure on the items before the middle. If it's after the middle item, repeat on the items after the middle. The method halves the number of items to check each time, so it finds it or determines it's not present in logarithmic time. 

-- from Wikipedia

here is my code:

 

 

1 #!/usr/bin/env python
2 # BSearch.py
3  
4  def BSearch(li, key):
5 """
6 Binary Search:
7 Stored the items in a sorted list
8 Algorithm: division of integers
9 return the floor of the quotient
10 """
11 low = 0
12 high = len(li) - 1
13 i = 0
14 while low <= high:
15 i = i + 1
16 mid = (low+high) / 2
17 if key == li[mid]: # found the key
18   print "Got %d with index[%d] in %d times." % (key, mid, i)
19 return
20 else:
21 if key < l[mid]: # key before the middle
22   high = mid -1
23 else: # key after the middle
24   low = mid + 1
25 else:
26 print "No key: %d " % key

27  if __name__ == "__main__":
28 print BSearch.__doc__
29 li = [1,2,3,4,5,6,7,8,9]
30 BSearch(li, 9)

 

Result:

 

1
2 Binary Search:
3 Stored the items in a sorted list
4 division of integers return the floor
5 of the quotient
6
7 Got 9 with index[8] in 4 times.
8  

 

Here is my another solution, with Recursion.

If you have a better one, please let me know.

 

1 #!/usr/bin/env python
2 # file name - BinarySearch.py
3  
4  def BSearch(li, key):
5 """
6 Binary Search: Use Recursion
7 but the solution cannot return the position
8 """
9 low = 0
10 high = len(li)
11 mid = (high+low) / 2
12 try:
13 if key == li[mid]:
14 print li[mid] # return the key you want, without its position
15   if key < li[mid]:
16 return BSearch(li[low:mid], key)
17 if key > li[mid]:
18 return BSearch(li[mid:high], key)
19 except:
20 print "Error occured, and key %d no found." % key
21
22  if __name__ == "__main__":
23 print BSearch.__doc__
24 BSearch([1,3,4,6,8,1000], 10)
25 BSearch([1,3,5,42,85,93,99,109,899], 109)

 

Result:

 

1
2 Binary Search: Use Recursion
3 but the solution cannot return the position
4
5 Error occured, and key 10 no found.
6  109
7  
posted on 2010-08-10 18:19  oyzway  阅读(3394)  评论(0编辑  收藏  举报