Smallest greater elements in whole array | Efficient Javascript program to find smallest greater element in whole array for every element . ; lowerbound function ; Driver code
function smallestGreater ( arr , n ) { let s = new Set ( ) ; for ( let i = 0 ; i < n ; i ++ ) s . add ( arr [ i ] ) ; let newAr = [ ] ; for ( let p of s . values ( ) ) { newAr . push ( p ) ; } newAr . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < n ; i ++ ) { let temp = lowerBound ( newAr , 0 , newAr . length , arr [ i ] ) ; if ( temp < n ) document . write ( newAr [ temp ] + " " ) ; else document . write ( " " ) ; } } function lowerBound ( vec , low , high , element ) { let array = [ ... vec ] ; while ( low < high ) { let middle = Math . floor ( low + ( high - low ) / 2 ) ; if ( element > array [ middle ] ) { low = middle + 1 ; } else { high = middle ; } } return low + 1 ; } let ar = [ 6 , 3 , 9 , 8 , 10 , 2 , 1 , 15 , 7 ] ; let n = ar . length ; smallestGreater ( ar , n ) ;