Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #create a binary search function
- numbers = [1,2,5,8,7,9,12,51,41,87,95,98,992,52,472,21,43]
- def sort_binarysearch(list_to_search,find):
- sortedlist = (list_to_search[:]) #create new list,a copy of (list_to_search), leave old intact
- sortedlist.sort() #sort new list
- print(sortedlist)
- position = 0 #keeps track of position in list relative to the total length
- left = 0 #makes position 0 in list == left
- right = len(sortedlist) - 1 #makes last item in list == right
- search = True
- while left <= right and search == True: #while left is smaller then right and search == True
- mid = int((left + right)/2) #mid = first position + last position / 2
- position = mid
- if sortedlist[mid] > find: #if sortedlist item is greater then find, right = mid -1
- right = mid - 1
- position = position - mid
- elif sortedlist[mid] < find: #elif sortedlist item is smaller then find,left = mid + 1
- left = mid + 1
- position = position + mid
- elif sortedlist[mid] == find: #sortedlist[ position or mid] == find, both work,so??
- print("Found " + str(find) + " at position " + str(position + 1))
- search = False
- else:
- search = False
- #print("Not found") #wont print, no matter what i try, a bit of a mystery
- sort_binarysearch(numbers,51)
Add Comment
Please, Sign In to add comment