Guest User

Untitled

a guest
Oct 22nd, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. def binary_search(array, left, right, key):
  4. mid = left + ((right - left) // 2) # finds the midpoint between left and right
  5.  
  6. if array[mid] == key:
  7. return mid # returns the index if the key is found
  8.  
  9. elif key < array[mid]:
  10. return binary_search(array, left, mid-1, key) # binary searches the left portion
  11.  
  12. elif key > array[mid]:
  13. return binary_search(array, mid, right, key) # binary searches the right portion
  14.  
  15. else:
  16. return -1
  17.  
  18. print("Enter the elements of the array")
  19. a = [int(n) for n in input().split()] # takes the array input
  20.  
  21. if a != a.sort(): # checks whether array is sorted
  22. a.sort() # if unsorted sorts the array
  23. print("The array is unsorted")
  24. print("The sorted array is...")
  25. print(a) # prints new sorted array
  26. else:
  27. print("The array is already sorted")
  28. print("The input array is...")
  29. print(a) # prints old sorted array
  30.  
  31. print("Enter the value to be searched for")
  32. key = int(input()) # asks for value to be binary searched
  33.  
  34. l = 0
  35. r = len(a) - 1
  36.  
  37. ans = binary_search(a, l, r, key)
  38.  
  39. if ans == -1:
  40. print("Value not found")
  41. else:
  42. print("Value found at index " + str(ans))
Add Comment
Please, Sign In to add comment