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 ; First element is the leftmost minimum in a sorted array ; Last element is the rightmost maximum in a sorted array
function getRightMin ( arr , n ) { let min = arr [ 0 ] ; let rightMin = 0 ; let 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 ) { let max = arr [ n - 1 ] ; let leftMax = n - 1 ; let i = n - 2 ; while ( i > 0 ) { if ( arr [ i ] == max ) leftMax = i ; i = parseInt ( i / 2 , 10 ) ; } i = leftMax - 1 ; while ( i >= 0 && arr [ i ] == max ) { leftMax = i ; i -- ; } return leftMax ; } let arr = [ 0 , 0 , 1 , 2 , 5 , 5 , 6 , 8 , 8 ] ; let n = arr . length ; document . write ( " " + 0 + " " ) ; document . write ( " " + getRightMin ( arr , n ) + " " ) ; document . write ( " " + getLeftMax ( arr , n ) + " " ) ; document . write ( " " + ( n - 1 ) ) ;