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 . ; Driver Code
function findFirst ( arr , n , x ) { var count = 0 ; var isX = false ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) { isX = true ; } else if ( arr [ i ] < x ) { count ++ ; } } return ( isX == false ) ? - 1 : count ; } var x = 20 , arr = [ 10 , 30 , 20 , 50 , 20 ] ; var n = arr . length ; document . write ( findFirst ( arr , n , x ) ) ;