Two elements whose sum is closest to zero | Modified to sort by abolute values ; Absolute value shows how close it is to zero ; If found an even close value update min and store the index ; Driver code
function findMinSum ( arr , n ) { for ( let i = 1 ; i < n ; i ++ ) { if ( ! ( Math . abs ( arr [ i - 1 ] ) < Math . abs ( arr [ i ] ) ) ) { let temp = arr [ i - 1 ] ; arr [ i - 1 ] = arr [ i ] ; arr [ i ] = temp ; } } let min = Number . MAX_VALUE ; let x = 0 , y = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( Math . abs ( arr [ i - 1 ] + arr [ i ] ) <= min ) { min = Math . abs ( arr [ i - 1 ] + arr [ i ] ) ; x = i - 1 ; y = i ; } } document . write ( " " + " " + arr [ x ] + " " + arr [ y ] ) ; } let arr = [ 1 , 60 , - 10 , 70 , - 80 , 85 ] ; let n = arr . length ; findMinSum ( arr , n ) ;