Sort an array without changing position of negative numbers - GeeksforGeeks

31 May, 2021
Given an array arr[] of N integers, the task is to sort the array without changing the position of negative numbers (if any) i.e. the negative numbers need not be sorted.Examples:  
Input: arr[] = {2, -6, -3, 8, 4, 1} Output: 1 -6 -3 2 4 8Input: arr[] = {-2, -6, -3, -8, 4, 1} Output: -2 -6 -3 -8 1 4 
Approach: Store all the non-negative elements of the array in another vector and sort this vector. Now, replace all the non-negative values in the original array with these sorted values.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sort the array such that// negative values do not get affectedvoid sortArray(int a[], int n){     // Store all non-negative values    vector<int> ans;    for (int i = 0; i < n; i++) {        if (a[i] >= 0)            ans.push_back(a[i]);    }     // Sort non-negative values    sort(ans.begin(), ans.end());     int j = 0;    for (int i = 0; i < n; i++) {         // If current element is non-negative then        // update it such that all the        // non-negative values are sorted        if (a[i] >= 0) {            a[i] = ans[j];            j++;        }    }     // Print the sorted array    for (int i = 0; i < n; i++)        cout << a[i] << " ";} // Driver codeint main(){    int arr[] = { 2, -6, -3, 8, 4, 1 };     int n = sizeof(arr) / sizeof(arr[0]);     sortArray(arr, n);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to sort the array such that// negative values do not get affectedstatic void sortArray(int a[], int n){     // Store all non-negative values    Vector<Integer> ans = new Vector<>();    for (int i = 0; i < n; i++)    {        if (a[i] >= 0)            ans.add(a[i]);    }     // Sort non-negative values    Collections.sort(ans);     int j = 0;    for (int i = 0; i < n; i++)    {         // If current element is non-negative then        // update it such that all the        // non-negative values are sorted        if (a[i] >= 0)        {            a[i] = ans.get(j);            j++;        }    }     // Print the sorted array    for (int i = 0; i < n; i++)        System.out.print(a[i] + " ");} // Driver codepublic static void main(String[] args){    int arr[] = { 2, -6, -3, 8, 4, 1 };     int n = arr.length;     sortArray(arr, n);}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # Function to sort the array such that# negative values do not get affecteddef sortArray(a, n):     # Store all non-negative values    ans=[]    for i in range(n):        if (a[i] >= 0):            ans.append(a[i])     # Sort non-negative values    ans = sorted(ans)     j = 0    for i in range(n):         # If current element is non-negative then        # update it such that all the        # non-negative values are sorted        if (a[i] >= 0):            a[i] = ans[j]            j += 1     # Print the sorted array    for i in range(n):        print(a[i],end = " ")  # Driver code arr = [2, -6, -3, 8, 4, 1] n = len(arr) sortArray(arr, n) # This code is contributed by mohit kumar 29
// C# implementation of above approachusing System.Collections.Generic;using System; class GFG{ // Function to sort the array such that// negative values do not get affectedstatic void sortArray(int []a, int n){     // Store all non-negative values    List<int> ans = new List<int>();    for (int i = 0; i < n; i++)    {        if (a[i] >= 0)            ans.Add(a[i]);    }     // Sort non-negative values    ans.Sort();     int j = 0;    for (int i = 0; i < n; i++)    {         // If current element is non-negative then        // update it such that all the        // non-negative values are sorted        if (a[i] >= 0)        {            a[i] = ans[j];            j++;        }    }     // Print the sorted array    for (int i = 0; i < n; i++)        Console.Write(a[i] + " ");} // Driver codepublic static void Main(String[] args){    int []arr = { 2, -6, -3, 8, 4, 1 };     int n = arr.Length;     sortArray(arr, n);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Function to sort the array such that// negative values do not get affectedfunction sortArray(a, n){     // Store all non-negative values    var ans = [];    for (var i = 0; i < n; i++) {        if (a[i] >= 0)            ans.push(a[i]);    }     // Sort non-negative values    ans.sort((a,b)=> a-b);     var j = 0;    for (var i = 0; i < n; i++) {         // If current element is non-negative then        // update it such that all the        // non-negative values are sorted        if (a[i] >= 0) {            a[i] = ans[j];            j++;        }    }     // Print the sorted array    for (var i = 0; i < n; i++)        document.write( a[i] + " ");} // Driver codevar arr = [2, -6, -3, 8, 4, 1];var n = arr.length;sortArray(arr, n);  </script>
1 -6 -3 2 4 8
 
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
29AjayKumar
mohit kumar 29
Akanksha_Rai
subhammahato348
itsok
Arrays
Competitive Programming
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming