Ordenar una array sin cambiar la posición de los números negativos

Dada una array arr[] de N enteros, la tarea es ordenar la array sin cambiar la posición de los números negativos (si los hay), es decir, no es necesario ordenar los números negativos.
Ejemplos: 
 

Entrada: arr[] = {2, -6, -3, 8, 4, 1} 
Salida: 1 -6 -3 2 4 8
Entrada: arr[] = {-2, -6, -3, -8, 4, 1} 
Salida: -2 -6 -3 -8 1 4 

Enfoque: almacene todos los elementos no negativos de la array en otro vector y ordene este vector. Ahora, reemplace todos los valores no negativos en la array original con estos valores ordenados.
A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the array such that
// negative values do not get affected
void 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 code
int main()
{
    int arr[] = { 2, -6, -3, 8, 4, 1 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    sortArray(arr, n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to sort the array such that
// negative values do not get affected
static 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 code
public 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

# Python3 implementation of the approach
 
# Function to sort the array such that
# negative values do not get affected
def 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#

// C# implementation of above approach
using System.Collections.Generic;
using System;
 
class GFG
{
 
// Function to sort the array such that
// negative values do not get affected
static 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 code
public 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

Javascript

<script>
 
// JavaScript implementation of the approach
 
// Function to sort the array such that
// negative values do not get affected
function 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 code
var arr = [2, -6, -3, 8, 4, 1];
var n = arr.length;
sortArray(arr, n);
 
 
</script>
Producción: 

1 -6 -3 2 4 8

 

Complejidad de tiempo: O(n * log n )

Espacio Auxiliar: O(n)

Publicación traducida automáticamente

Artículo escrito por Chandan_Agrawal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *