Difference between revisions of "CSC111 BinarySearch.py"
Line 22: | Line 22: | ||
def binsearch( A, low, high, key ): | def binsearch( A, low, high, key ): | ||
"""a recursive function that searches the list A to see if | """a recursive function that searches the list A to see if | ||
− | it contains the item key between the indexes "low" and "high" | + | it contains the item key between the indexes "low" and "high". |
+ | returns the index where the key was found, or -1 otherwise | ||
""" | """ | ||
if low>high: | if low>high: | ||
− | return | + | return -1 |
mid = ( low + high )/2 | mid = ( low + high )/2 | ||
if A[mid]==key: | if A[mid]==key: | ||
− | return | + | return mid |
if key < A[mid]: | if key < A[mid]: | ||
Line 49: | Line 50: | ||
print | print | ||
key = int( input( "search for what number? " ) ) | key = int( input( "search for what number? " ) ) | ||
− | + | index = binsearch( A, 0, len( A )-1, key ) | |
− | if | + | if index != -1: |
print( "found %d at index %d" % ( key, index ) ) | print( "found %d at index %d" % ( key, index ) ) | ||
else: | else: |
Revision as of 20:42, 28 April 2014
--D. Thiebaut 13:05, 26 April 2010 (UTC)
# binarySearch.py
# D. Thiebaut
#
# Searches a sorted array of random numbers for a number.
from random import randrange
#------------------------------------------------------------------
def createArray( n ):
"""Creates a list of n random numbers in sorted order"""
A= []
for i in range( n ):
A.append( randrange( n * 10 ) )
A.sort()
return A
#------------------------------------------------------------------
def binsearch( A, low, high, key ):
"""a recursive function that searches the list A to see if
it contains the item key between the indexes "low" and "high".
returns the index where the key was found, or -1 otherwise
"""
if low>high:
return -1
mid = ( low + high )/2
if A[mid]==key:
return mid
if key < A[mid]:
return binsearch( A, low, mid-1, key )
else:
return binsearch( A, mid+1, high, key )
#------------------------------------------------------------------
def main():
"""prompts the user for a number and returns wether the number is
in the list or not"""
A = createArray( 20 )
print( A )
while True:
print
key = int( input( "search for what number? " ) )
index = binsearch( A, 0, len( A )-1, key )
if index != -1:
print( "found %d at index %d" % ( key, index ) )
else:
print( "%d not in A" % key )
main()