Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active January 21, 2017 20:05
Show Gist options
  • Save anil477/60593cde4df6464eb127e456389d35ae to your computer and use it in GitHub Desktop.
Save anil477/60593cde4df6464eb127e456389d35ae to your computer and use it in GitHub Desktop.
Find pivot and minimum element in a sorted rotated array. Also find how many times was the sorted array rotated.
class Search:
def __init__(self):
# self.array = [3, 4, 5, 6, 7, 8, 1, 2]
# self.array = [3, 4, 5, 6, 7, 8,9, 10,11,12, 0,1,2]
self.array = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]
def search(self, low, high):
# if the entire array is sorted then pivot point is 0
if self.array[low] < self.array[high]:
return 0
if len(self.array) == 0:
return -1
while low <= high:
mid = (low + high) / 2
# if mid is pivot return
if mid < len(self.array) - 1 and self.array[mid] > self.array[mid + 1]:
return mid
# if left of mid is sorted then goto the unsorted part
if self.array[low] <= self.array[mid]:
# left is sorted, go right
low = mid + 1
else:
# right is sorted, go left
high = mid - 1
def start(self):
pivot = self.search(0, len(self.array) - 1)
if pivot == 0:
print "Smallest ", self.array[pivot]
print "Roated ", pivot, "times"
print "Pivoted Around ", self.array[pivot]
else:
print pivot
print "Smallest ", self.array[pivot + 1]
print "Roated ", pivot + 1, "times"
print "Pivoted Around ", self.array[pivot]
s = Search()
s.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment