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
< ? php function getRightMin ( $ arr , $ n ) { $ min = $ arr [ 0 ] ; $ rightMin = 0 ; $ i = 1 ; while ( $ i < $ n ) { if ( $ arr [ $ i ] == $ min ) $ rightMin = $ i ; $ i *= 2 ; } $ i = $ rightMin + 1 ; while ( $ i < $ n && $ arr [ $ i ] == $ min ) { $ rightMin = $ i ; $ i ++ ; } return $ rightMin ; } function getLeftMax ( $ arr , $ n ) { $ max = $ arr [ $ n - 1 ] ; $ leftMax = $ n - 1 ; $ i = $ n - 2 ; while ( $ i > 0 ) { if ( $ arr [ $ i ] == $ max ) $ leftMax = $ i ; $ i /= 2 ; } $ i = $ leftMax - 1 ; while ( $ i >= 0 && $ arr [ $ i ] == $ max ) { $ leftMax = $ i ; $ i -- ; } return $ leftMax ; } $ arr = array ( 0 , 0 , 1 , 2 , 5 , 5 , 6 , 8 , 8 ) ; $ n = sizeof ( $ arr ) ; echo " Minimum ▁ left ▁ : ▁ " , 0 , " STRNEWLINE " ; echo " Minimum ▁ right ▁ : ▁ " , getRightMin ( $ arr , $ n ) , " STRNEWLINE " ; echo " Maximum ▁ left ▁ : ▁ " , getLeftMax ( $ arr , $ n ) , " STRNEWLINE " ; echo " Maximum ▁ right ▁ : ▁ " , ( $ n - 1 ) , " STRNEWLINE " ; ? >