Find index of first occurrence when an unsorted array is sorted | Javascript program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ;  ; Driver code
function findFirst ( arr , n , x ) { arr . sort ( ) ; let ptr = lowerBound ( arr , 0 , n , x ) ; return ( arr [ ptr ] != x ) ? - 1 : ( ptr ) ; } function lowerBound ( a , low , high , element ) { while ( low < high ) { let middle = low + parseInt ( ( high - low ) / 2 , 10 ) ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } let x = 20 ; let arr = [ 10 , 30 , 20 , 50 , 20 ] ; let n = arr . length ; document . write ( findFirst ( arr , n , x ) ) ;