kevinbocky

sort_search_binairy.py

Jan 31st, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #create a binary search function
  2. numbers = [1,2,5,8,7,9,12,51,41,87,95,98,992,52,472,21,43]
  3.  
  4.  
  5. def sort_binarysearch(list_to_search,find):
  6. sortedlist = (list_to_search[:]) #create new list,a copy of (list_to_search), leave old intact
  7. sortedlist.sort() #sort new list
  8. print(sortedlist)
  9. position = 0 #keeps track of position in list relative to the total length
  10. left = 0 #makes position 0 in list == left
  11. right = len(sortedlist) - 1 #makes last item in list == right
  12. search = True
  13. while left <= right and search == True: #while left is smaller then right and search == True
  14. mid = int((left + right)/2) #mid = first position + last position / 2
  15. position = mid
  16. if sortedlist[mid] > find: #if sortedlist item is greater then find, right = mid -1
  17. right = mid - 1
  18. position = position - mid
  19. elif sortedlist[mid] < find: #elif sortedlist item is smaller then find,left = mid + 1
  20. left = mid + 1
  21. position = position + mid
  22. elif sortedlist[mid] == find: #sortedlist[ position or mid] == find, both work,so??
  23. print("Found " + str(find) + " at position " + str(position + 1))
  24. search = False
  25. else:
  26. search = False
  27. #print("Not found") #wont print, no matter what i try, a bit of a mystery
  28.  
  29.  
  30.  
  31.  
  32.  
  33. sort_binarysearch(numbers,51)
Add Comment
Please, Sign In to add comment