Minimum index i such that all the elements from index i to given index are equal | Function to return the minimum required index ; Short - circuit more comparisions as found the border point ; For cases were high = low + 1 and arr [ high ] will match with arr [ pos ] but not arr [ low ] or arr [ mid ] . In such iteration the if condition will satisfy and loop will break post that low will be updated . Hence i will not povar to the correct index . ; Driver code
function minIndex ( arr , pos ) { var low = 0 ; var high = pos ; var i = pos ; while ( low < high ) { var mid = parseInt ( ( low + high ) / 2 ) ; if ( arr [ mid ] != arr [ pos ] ) { low = mid + 1 ; } else { high = mid - 1 ; i = mid ; if ( mid > 0 && arr [ mid - 1 ] != arr [ pos ] ) { break ; } } } return arr [ low ] == arr [ pos ] ? low : i ; } var arr = [ 2 , 1 , 1 , 1 , 5 , 2 ] ;