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

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:
- Â Â Take the input array arr[] of size N as input.
- Â Â Use the inbuilt sort function to sort the array in ascending order based on the absolute values of the elements.
- Â Â 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] + " ");        }    }} |
-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 sortvoid 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 Codeint 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 approachimport 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 sortdef 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 Codearr = [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 approachusing 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> |
-5 -4 -2 1 3 6
Time complexity: O(N)
Auxiliary Space: O(N)Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



