Difference between revisions of "CSC231 binarySearch.py"
(New page: --~~~~ ---- <code><pre> #! /usr/bin/python # binarySearch.py # D. Thiebaut # searches and array using recursive binary search def search( key, A, left, right ): """The recursive fun...) |
|||
Line 2: | Line 2: | ||
---- | ---- | ||
− | < | + | ::<source lang="python"> |
#! /usr/bin/python | #! /usr/bin/python | ||
# binarySearch.py | # binarySearch.py | ||
Line 43: | Line 43: | ||
main() | main() | ||
− | </ | + | </source> |
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | [[Category:CSC231]][[Category:Python]] |
Latest revision as of 10:53, 30 April 2017
--D. Thiebaut 18:03, 23 November 2008 (UTC)
#! /usr/bin/python # binarySearch.py # D. Thiebaut # searches and array using recursive binary search def search( key, A, left, right ): """The recursive function""" if left > right: return -1 mid = ( left + right ) / 2 if A[mid] == key: return mid if key < A[mid]: return search( key, A, left, mid-1 ) else: return search( key, A, mid+1, right ) def main(): """Creates an array and allows user to search it""" A = [1, 3, 10, 4, -1, 10, -20, 100, 12, 13, 15, 5, 6] A.sort( ) print A while True: try: key = input( "Enter key (Press Enter to stop)> " ) except: break index = search( key, A, 0, len( A )-1 ) if index==-1: print "not found!" else: print "found %d at Index %d" % ( key, index ) main()