Sort an array without changing position of negative numbers | Function to sort the array such that negative values do not get affected ; Store all non - negative values ; Sort non - negative values ; If current element is non - negative then update it such that all the non - negative values are sorted ; Print the sorted array ; Driver code
function sortArray ( a , n ) { var ans = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) ans . push ( a [ i ] ) ; } ans . sort ( ( a , b ) => a - b ) ; var j = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) { a [ i ] = ans [ j ] ; j ++ ; } } for ( var i = 0 ; i < n ; i ++ ) document . write ( a [ i ] + " " ) ; } var arr = [ 2 , - 6 , - 3 , 8 , 4 , 1 ] ; var n = arr . length ; sortArray ( arr , n ) ;