Reverse an array without using subtract sign â €˜ | Function to reverse array ; Reverse array in simple manner ; Swap ith index value with ( n - i - 1 ) th index value Note : A - B = A + ~ B + 1 So n - i = n + ~ i + 1 then n - i - 1 = ( n + ~ i + 1 ) + ~ 1 + 1 ; Driver code ; print the reversed array
function reverseArray ( arr , n ) { for ( let i = 0 ; i < parseInt ( n / 2 , 10 ) ; i ++ ) { swap ( arr , i , ( n + ~ i + 1 ) + ~ 1 + 1 ) ; } } function swap ( arr , i , j ) { let temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } let arr = [ 5 , 3 , 7 , 2 , 1 , 6 ] ; let n = arr . length ; reverseArray ( arr , n ) ; for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; }