Rearrange array to make product of prefix sum array non zero | Function to print array elements ; Function to rearrange array that satisfies the given condition ; Stores sum of elements of the given array ; Calculate totalSum ; If the totalSum is equal to 0 ; No possible way to rearrange array ; If totalSum exceeds 0 ; Rearrange the array in descending order ; Otherwise ; Rearrange the array in ascending order ; Driver Code
function printArr ( arr , N ) { for ( var i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } function rearrangeArr ( arr , N ) { var totalSum = 0 ; for ( var i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } if ( totalSum == 0 ) { document . write ( " " + " " ) ; } else if ( totalSum > 0 ) { arr . sort ( compare ) ; arr = reverse ( arr ) ; printArr ( arr , N ) ; } else { arr . sort ( compare ) ; printArr ( arr , N ) ; } } function compare ( a , b ) { if ( a < b ) { return - 1 ; } else if ( a > b ) { return 1 ; } else { return 0 ; } } function reverse ( a ) { var i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } var arr = [ 1 , - 1 , - 2 , 3 ] ; var N = arr . length ; rearrangeArr ( arr , N ) ;