Smallest greater elements in whole array | Simple Javascript program to find smallest greater element in whole array for every element . ; Find the closest greater element for arr [ j ] in the entire array . ; Check if arr [ i ] is largest ; Driver code
function smallestGreater ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) { let diff = Number . MAX_VALUE ; let closest = - 1 ; for ( let j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] && arr [ j ] - arr [ i ] < diff ) { diff = arr [ j ] - arr [ i ] ; closest = j ; } } if ( closest == - 1 ) document . write ( " " ) ; else document . write ( arr [ closest ] + " " ) ; } } let ar = [ 6 , 3 , 9 , 8 , 10 , 2 , 1 , 15 , 7 ] ; let n = ar . length ; smallestGreater ( ar , n ) ;