Open In App

Sort given Array which is already Sorted based on absolute values of elements

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, sorted based on the absolute value of its elements. The task is to sort this array based on the actual values of the elements.

Examples: 

Input:  arr[] = {5, -7, 10, -11, 18}
Output: -11, -7, 5, 10, 18
Explanation: When the array is sorted the negative values will come at the beginning of the array.

Input:  arr[] = {1, -2, -3, 4, -5}
Output: -5, -3, -2, 1, 4

 

Naive Approach:

The naive approach to solve the problem is to use inbuilt sort function to sort the array.

Algorithm:

  1.    Take the input array arr[] of size N as input.
  2.    Use the inbuilt sort function to sort the array in ascending order based on the absolute values of the elements.
  3.    Print the sorted array.

Below is the implementation of the approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
// Driver code
int main() {
      // Input array
    int arr[] = { 1, -2, 3, -4, -5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
   
      // sort array in ascending order
    sort(arr, arr + n);
       
      // print the final array elements
    for(int i=0; i<n; i++) {
        cout<<arr[i]<<" ";
    }
   
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args) {
        // Input array
        int[] arr = {1, -2, 3, -4, -5, 6};
        int n = arr.length;
 
        // Sort the array in ascending order
        Arrays.sort(arr);
 
        // Print the final array elements
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}


Python3




# Import the necessary module for sorting
from typing import List
 
def main():
    # Input array
    arr: List[int] = [1, -2, 3, -4, -5, 6]
    n: int = len(arr)
 
    # Sort array in ascending order
    arr.sort()
 
    # Print the final array elements
    for i in range(n):
        print(arr[i], end=" ")
 
if __name__ == "__main__":
    # Driver code
    main()


C#




using System;
 
class Program
{
    static void Main()
    {
        // Input array
        int[] arr = { 1, -2, 3, -4, -5, 6 };
        int n = arr.Length;
 
        // Sort array in ascending order
        Array.Sort(arr);
 
        // Print the final array elements
        foreach (var element in arr)
        {
            Console.Write(element + " ");
        }
 
        Console.WriteLine();
    }
}


Javascript




// Input array
let arr = [1, -2, 3, -4, -5, 6];
let n = arr.length;
 
// Sort the array in ascending order
arr.sort((a, b) => a - b);
 
// Print the final array elements
for (let i = 0; i < n; i++) {
    console.log(arr[i] + " ");
}


Output

-5 -4 -2 1 3 6 

Time Complexity: O(N*logN) as sort function has been called. Here, N is size of input array.
Space Complexity: O(1) as no extra space has been used.

Approach: This problem can be solved using double ended queue. The idea is to traverse the array from left to right and insert the negative elements in the front and the positive elements in the back of the deque. Now pop the elements from the front of the deque to fill the array and get the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <deque>
#include <iostream>
using namespace std;
 
// Function to sort
void SortWithoutSorting(int arr[], int N)
{
    deque<int> dq;
    for (int i = 0; i < N; i++) {
 
        // Pushing negative elements in
        // the front of the deque
        if (arr[i] < 0) {
            dq.push_front(arr[i]);
        }
 
        // Pushing positive elements in
        // the back of the deque
        else {
            dq.push_back(arr[i]);
        }
    }
 
    // Preparing the output array
    int i = 0;
    for (auto it = dq.begin(); it !=
         dq.end(); it++)
        arr[i++] = *it;
}
 
// Function to print the array.
void showArray(int arr[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, -2, 3, -4, -5, 6 };
    int N = sizeof(arr) / sizeof(int);
 
    SortWithoutSorting(arr, N);
    showArray(arr, N);
    return 0;
}


Java




// Java Program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to sort
    public static void SortWithoutSorting(int arr[], int N)
    {
        Deque<Integer> dq = new ArrayDeque<Integer>();
        for (int i = 0; i < N; i++) {
     
            // Pushing negative elements in
            // the front of the deque
            if (arr[i] < 0) {
                dq.addFirst(arr[i]);
            }
     
            // Pushing positive elements in
            // the back of the deque
            else {
                dq.addLast(arr[i]);
            }
        }
     
        // Preparing the output array
        int i = 0;
        for (Iterator it = dq.iterator();
             it.hasNext();) {
            arr[i++] = (int)it.next();
        }
         
    }
     
    // Function to print the array.
    public static void showArray(int arr[], int N)
    {
        for (int i = 0; i < N; i++) {
            System.out.print(arr[i] + " ");
        }
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int arr[] = { 1, -2, 3, -4, -5, 6 };
        int N = arr.length;
     
        SortWithoutSorting(arr, N);
        showArray(arr, N);
    }
}
 
// This code is contributed by Shubham Singh


Python3




# Python code for the above approach
 
# Function to sort
def SortWithoutSorting(arr, N):
     
    dq = []
    for i in range(N):
        # Pushing negative elements in
        # the front of the deque
        if (arr[i] < 0):
            dq.insert(0,arr[i])
             
        # Pushing positive elements in
        # the back of the deque
        else:
            dq.append(arr[i])
             
    # Preparing the output array
    i = 0
    for it in dq:
        arr[i] = it
        i += 1
         
    return arr
 
# Function to print the array.
def showArray(arr, N):
    for i in range(N):
        print(arr[i], end= " ")
     
# Driver Code
arr = [1, -2, 3, -4, -5, 6]
N = len(arr)
 
arr = SortWithoutSorting(arr, N)
showArray(arr, N)
 
# This code is contributed by Shubham Singh


C#




// C# Program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to sort
  public static void SortWithoutSorting(int[] arr, int N)
  {
 
    List<int> dq = new List<int>();
    int i;
    for (i = 0; i < N; i++) {
 
      // Pushing negative elements in
      // the front of the deque
      if (arr[i] < 0) {
        dq.Insert(0,arr[i]);
      }
 
      // Pushing positive elements in
      // the back of the deque
      else {
        dq.Add(arr[i]);
      }
    }
 
    // Preparing the output array
    i = 0;
    foreach(int it in dq) {
      arr[i++] = it;
    }
 
  }
 
  // Function to print the array.
  public static void showArray(int[] arr, int N)
  {
    for (int i = 0; i < N; i++) {
      Console.Write(arr[i] + " ");
    }
  }
 
  // Driver Code
  public static void Main ()
  {
    int[] arr = { 1, -2, 3, -4, -5, 6 };
    int N = arr.Length;
 
    SortWithoutSorting(arr, N);
    showArray(arr, N);
  }
}
 
// This code is contributed by Shubham Singh


Javascript




<script>
      // JavaScript code for the above approach
 
      // Function to sort
      function SortWithoutSorting(arr, N)
      {
          let dq = [];
          for (let i = 0; i < N; i++) {
 
              // Pushing negative elements in
              // the front of the deque
              if (arr[i] < 0) {
                  dq.unshift(arr[i]);
              }
 
              // Pushing positive elements in
              // the back of the deque
              else {
                  dq.push(arr[i]);
              }
          }
 
          // Preparing the output array
          let i = 0;
          for (let it of dq)
              arr[i++] = it;
      }
 
      // Function to print the array.
      function showArray(arr, N) {
          for (let i = 0; i < N; i++) {
              document.write(arr[i] + " ")
          }
      }
 
      // Driver Code
      let arr = [1, -2, 3, -4, -5, 6];
      let N = arr.length;
 
      SortWithoutSorting(arr, N);
      showArray(arr, N);
 
// This code is contributed by Potta Lokesh
  </script>


Output

-5 -4 -2 1 3 6 





Time complexity: O(N)
Auxiliary Space: O(N) 



Last Updated : 17 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads