Leftmost and rightmost indices of the maximum and the minimum element of an array | Function to return the index of the rightmost minimum element from the array ; First element is the minimum in a sorted array ; While the elements are equal to the minimum update rightMin ; Final check whether there are any elements which are equal to the minimum ; Function to return the index of the leftmost maximum element from the array ; Last element is the maximum in a sorted array ; While the elements are equal to the maximum update leftMax ; Final check whether there are any elements which are equal to the maximum ; Driver code ; First element is the leftmost minimum in a sorted array ; Last element is the rightmost maximum in a sorted array
def getRightMin ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE rightMin = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] == min ) : NEW_LINE INDENT rightMin = i NEW_LINE DEDENT i *= 2 NEW_LINE DEDENT i = rightMin + 1 NEW_LINE while ( i < n and arr [ i ] == min ) : NEW_LINE INDENT rightMin = i NEW_LINE i += 1 NEW_LINE DEDENT return rightMin NEW_LINE DEDENT def getLeftMax ( arr , n ) : NEW_LINE INDENT max = arr [ n - 1 ] NEW_LINE leftMax = n - 1 NEW_LINE i = n - 2 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] == max ) : NEW_LINE INDENT leftMax = i NEW_LINE DEDENT i = int ( i / 2 ) NEW_LINE DEDENT i = leftMax - 1 NEW_LINE while ( i >= 0 and arr [ i ] == max ) : NEW_LINE INDENT leftMax = i NEW_LINE i -= 1 NEW_LINE DEDENT return leftMax NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 0 , 1 , 2 , 5 , 5 , 6 , 8 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ left ▁ : " , 0 ) NEW_LINE print ( " Minimum ▁ right ▁ : " , getRightMin ( arr , n ) ) NEW_LINE print ( " Maximum ▁ left ▁ : " , getLeftMax ( arr , n ) ) NEW_LINE print ( " Maximum ▁ right ▁ : " , ( n - 1 ) ) NEW_LINE DEDENT