Solution: Search in a Rotated List
Let's look at a detailed analysis of all the ways to search in a rotated list.
We'll cover the following...
Solution: pivoted binary search
Think of it this way: a sorted and then rotated list is essentially made up of two sorted sublists. How can we leverage that fact to write a solution that uses a binary search?
def pivoted_binary_search(lst, n, key):"""Function to search key in a list:param lst: A list of integers:param n: The size of the list:param key: A key to be searched in the list"""pivot = find_pivot_point(lst, 0, n - 1)# If the list is not rotatedif pivot == -1:return binary_search(lst, 0, n - 1, key)# If the list is rotated then find the elements in left sided and right sided listif lst[pivot] == key:return pivotif lst[0] <= key:return binary_search(lst, 0, pivot - 1, key)return binary_search(lst, pivot + 1, n - 1, key)def find_pivot_point(lst, low, high):"""Function to pivot in the list:param lst: A list of integers:param low: Lowest index of the list:param high: Highest index of the list"""# base casesif high < low:return -1if high == low:return lowmid = (low + high) // 2if mid < high and lst[mid] > lst[mid + 1]:return midif mid > low and lst[mid] < lst[mid - 1]:return mid - 1if lst[low] >= lst[mid]:return find_pivot_point(lst, low, mid - 1)return find_pivot_point(lst, mid + 1, high)def binary_search(lst, low, high, key):"""Binary Search function:param lst: A list of integers:param low: Lowest index of the list:param high: Highest index of the list:param key: A key to be searched in the list"""if high < low:return -1mid = (low + high) // 2if key == lst[mid]:return midif key > lst[mid]:return binary_search(lst, (mid + 1), high, key)return binary_search(lst, low, (mid - 1), key)# Driver to test above codeif __name__ == '__main__':lst = [6, 7, 8, 9, 10, 0, 1, 2, 3]key = 0print("Index of the element is : ",pivoted_binary_search(lst, len(lst), key))
Explanation
This algorithm first finds the point where the list is rotated. If the ...