Advertisement
Guest User

binarysearch

a guest
Sep 26th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. import math
  2.  
  3. def bin_search(array, num, array_offset):
  4.     max = len(array)-1
  5.     min = 0
  6.     result = -1
  7.    
  8.     index = lambda x: (x+array_offset)%len(array)
  9.    
  10.     if array[index(min)] <= num <= array[index(max)]:
  11.         for x in range(0, math.ceil(math.log(len(array)))):
  12.             mid = math.floor((min+max)/2)
  13.             if array[index(mid)] is num:
  14.                 result = index(mid)
  15.                 break
  16.             elif array[index(mid)] < num:
  17.                 min = mid + 1
  18.             else:
  19.                 max = mid - 1
  20.     return result
  21.  
  22. def shift_array(array, offset):
  23.     for i in range(0, offset):
  24.         array.insert(0, array.pop())
  25.  
  26. k = 1
  27. arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  28.  
  29. shift_array(arr, k)
  30.  
  31. print(arr)
  32.  
  33. print(bin_search(arr, 8, k))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement