Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 20 Jan, 2022

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

 

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) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!