Sort an array without changing position of negative numbers | C # implementation of above approach ; 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
using System . Collections . Generic ; using System ; class GFG { static void sortArray ( int [ ] a , int n ) { List < int > ans = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) ans . Add ( a [ i ] ) ; } ans . Sort ( ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) { a [ i ] = ans [ j ] ; j ++ ; } } for ( int i = 0 ; i < n ; i ++ ) Console . Write ( a [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , - 6 , - 3 , 8 , 4 , 1 } ; int n = arr . Length ; sortArray ( arr , n ) ; } }