126 Introduction to Computational Models with Python
Listing 7.10 shows the Python script that implements the binary search
algorithm. The script commands are stored in command file bsearch.py.
Listing 7.10: Python script for sea rching for a key using binary search.
1 # Python script that implements a binary search
2 # of list (array) llist using key value key.
3 # The result is the index value of
4 # the element found, or -1 if not found.
5 # File: bsearch.py
6
7 def bsearchf (varr, kval):
8 # find the element in varr equal to kval
9 num = len (varr)
10 lower = 0
11 upper = num - 1
12 while lower <= upper :
13 middle = (lower + upper) / 2
14 if kval == varr[middle]:
15 return middle; # result
16 else:
17 if kval < varr[middle]:
18 upper = middle - 1
19 else: ...