Sort an array without changing position of negative numbers | C ++ implementation of the 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArray ( int a [ ] , int n ) { vector < int > ans ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) ans . push_back ( a [ i ] ) ; } sort ( ans . begin ( ) , ans . end ( ) ) ; 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 ++ ) cout << a [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 2 , -6 , -3 , 8 , 4 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , n ) ; return 0 ; }