Two elements whose sum is closest to zero | C # implementation using STL ; 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
using System ; class GFG { static void findMinSum ( int [ ] arr , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( ! ( Math . Abs ( arr [ i - 1 ] ) < Math . Abs ( arr [ i ] ) ) ) { int temp = arr [ i - 1 ] ; arr [ i - 1 ] = arr [ i ] ; arr [ i ] = temp ; } } int min = Int32 . MaxValue ; int x = 0 , y = 0 ; for ( int 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 ; } } Console . WriteLine ( " The ▁ two ▁ elements ▁ whose ▁ " + " sum ▁ is ▁ minimum ▁ are ▁ " + arr [ x ] + " ▁ and ▁ " + arr [ y ] ) ; } static void Main ( ) { int [ ] arr = { 1 , 60 , - 10 , 70 , - 80 , 85 } ; int n = arr . Length ; findMinSum ( arr , n ) ; } }