Find the minimum element in a sorted and rotated array | Python program to find minimum element in a sorted and rotated array ; This condition is needed to handle the case when array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum element . Consider the cases like [ 3 , 4 , 5 , 1 , 2 ] ; Check if mid itself is minimum element ; Decide whether we need to go to left half or right half ; Driver program to test above functions
def findMin ( arr , low , high ) : NEW_LINE INDENT if high < low : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT if high == low : NEW_LINE INDENT return arr [ low ] NEW_LINE DEDENT mid = int ( ( low + high ) / 2 ) NEW_LINE if mid < high and arr [ mid + 1 ] < arr [ mid ] : NEW_LINE INDENT return arr [ mid + 1 ] NEW_LINE DEDENT if mid > low and arr [ mid ] < arr [ mid - 1 ] : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if arr [ high ] > arr [ mid ] : NEW_LINE INDENT return findMin ( arr , low , mid - 1 ) NEW_LINE DEDENT return findMin ( arr , mid + 1 , high ) NEW_LINE DEDENT arr1 = [ 5 , 6 , 1 , 2 , 3 , 4 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr1 , 0 , n1 - 1 ) ) ) NEW_LINE arr2 = [ 1 , 2 , 3 , 4 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr2 , 0 , n2 - 1 ) ) ) NEW_LINE arr3 = [ 1 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr3 , 0 , n3 - 1 ) ) ) NEW_LINE arr4 = [ 1 , 2 ] NEW_LINE n4 = len ( arr4 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr4 , 0 , n4 - 1 ) ) ) NEW_LINE arr5 = [ 2 , 1 ] NEW_LINE n5 = len ( arr5 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr5 , 0 , n5 - 1 ) ) ) NEW_LINE arr6 = [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ] NEW_LINE n6 = len ( arr6 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr6 , 0 , n6 - 1 ) ) ) NEW_LINE arr7 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE n7 = len ( arr7 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr7 , 0 , n7 - 1 ) ) ) NEW_LINE arr8 = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 1 ] NEW_LINE n8 = len ( arr8 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr8 , 0 , n8 - 1 ) ) ) NEW_LINE arr9 = [ 3 , 4 , 5 , 1 , 2 ] NEW_LINE n9 = len ( arr9 ) NEW_LINE print ( " The ▁ minimum ▁ element ▁ is ▁ " + str ( findMin ( arr9 , 0 , n9 - 1 ) ) ) NEW_LINE