Sort array after converting elements to their squares
Last Updated :
03 Mar, 2024
Given an array of both positive and negative integers ‘arr[]’ which are sorted. The task is to sort the square of the numbers of the Array.
Examples:
Input : arr[] = {-6, -3, -1, 2, 4, 5}
Output : 1, 4, 9, 16, 25, 36
Input : arr[] = {-5, -4, -2, 0, 1}
Output : 0, 1, 4, 16, 25
Simple solution is to first convert each array element into its square and then apply any “O(nlogn)” sorting algorithm to sort the array elements.
Below is the implementation of the above idea
C++
#include <bits/stdc++.h>
using namespace std;
void sortSquares( int arr[], int n)
{
for ( int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
sort(arr, arr + n);
}
int main()
{
int arr[] = { -6, -3, -1, 2, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Before sort " << endl;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
sortSquares(arr, n);
cout << "\nAfter Sort " << endl;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
public static void sortSquares( int arr[])
{
int n = arr.length;
for ( int i = 0 ; i < n; i++)
arr[i] = arr[i] * arr[i];
Arrays.sort(arr);
}
public static void main(String[] args)
{
int arr[] = { - 6 , - 3 , - 1 , 2 , 4 , 5 };
int n = arr.length;
System.out.println( "Before sort " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
sortSquares(arr);
System.out.println( "" );
System.out.println( "After Sort " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
C#
using System;
class GFG {
public static void sortSquares( int [] arr)
{
int n = arr.Length;
for ( int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
Array.Sort(arr);
}
public static void Main()
{
int [] arr = { -6, -3, -1,
2, 4, 5 };
int n = arr.Length;
Console.WriteLine( "Before sort " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
sortSquares(arr);
Console.WriteLine( "" );
Console.WriteLine( "After Sort " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function sortSquares(arr)
{
let n = arr.length;
for (let i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
arr.sort();
}
let arr = [ -6, -3, -1, 2, 4, 5 ];
let n = arr.length;
document.write( "Before sort " + "<br/>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
sortSquares(arr);
document.write( "" + "<br/>" );
document.write( "After Sort " + "<br/>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
Python3
def sortSquare(arr, n):
for i in range (n):
arr[i] = arr[i] * arr[i]
arr.sort()
arr = [ - 6 , - 3 , - 1 , 2 , 4 , 5 ]
n = len (arr)
print ( "Before sort" )
for i in range (n):
print (arr[i], end = " " )
print ( "\n" )
sortSquare(arr, n)
print ( "After sort" )
for i in range (n):
print (arr[i], end = " " )
|
Output
Before sort
-6 -3 -1 2 4 5
After Sort
1 4 9 16 25 36
Time complexity: O(n log n) assuming that we use a O(n Log n) auxiliary space sorting algorithm
Auxiliary Space : O(1) assuming that we use a O(1) auxiliary space sorting algorithm
Efficient solution is based on the fact that the given array is already sorted. We do the following two steps.
- Divide the array into two-part “Negative and positive “.
- Use merge function to merge two sorted arrays into a single sorted array.
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
void sortSquares( int arr[], int n)
{
int K = 0;
for (K = 0; K < n; K++)
if (arr[K] >= 0)
break ;
int i = K - 1;
int j = K;
int ind = 0;
int temp[n];
while (i >= 0 && j < n) {
if (arr[i] * arr[i] < arr[j] * arr[j]) {
temp[ind] = arr[i] * arr[i];
i--;
}
else {
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
while (i >= 0) {
temp[ind] = arr[i] * arr[i];
i--;
ind++;
}
while (j < n) {
temp[ind] = arr[j] * arr[j];
j++;
ind++;
}
for ( int i = 0; i < n; i++)
arr[i] = temp[i];
}
int main()
{
int arr[] = { -6, -3, -1, 2, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Before sort " << endl;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
sortSquares(arr, n);
cout << "\nAfter Sort " << endl;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
public static void sortSquares( int arr[])
{
int n = arr.length;
int k;
for (k = 0 ; k < n; k++) {
if (arr[k] >= 0 )
break ;
}
int i = k - 1 ;
int j = k;
int ind = 0 ;
int [] temp = new int [n];
while (i >= 0 && j < n) {
if (arr[i] * arr[i] < arr[j] * arr[j]) {
temp[ind] = arr[i] * arr[i];
i--;
}
else {
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
while (i >= 0 ) {
temp[ind++] = arr[i] * arr[i];
i--;
}
while (j < n) {
temp[ind++] = arr[j] * arr[j];
j++;
}
for ( int x = 0 ; x < n; x++)
arr[x] = temp[x];
}
public static void main(String[] args)
{
int arr[] = { - 6 , - 3 , - 1 , 2 , 4 , 5 };
int n = arr.length;
System.out.println( "Before sort " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
sortSquares(arr);
System.out.println( "" );
System.out.println( "After Sort " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
C#
using System;
class GFG {
public static void sortSquares( int [] arr)
{
int n = arr.Length;
int k;
for (k = 0; k < n; k++) {
if (arr[k] >= 0)
break ;
}
int i = k - 1;
int j = k;
int ind = 0;
int [] temp = new int [n];
while (i >= 0 && j < n) {
if (arr[i] * arr[i] < arr[j] * arr[j]) {
temp[ind] = arr[i] * arr[i];
i--;
}
else {
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
while (i >= 0) {
temp[ind++] = arr[i] * arr[i];
i--;
}
while (j < n) {
temp[ind++] = arr[j] * arr[j];
j++;
}
for ( int x = 0; x < n; x++)
arr[x] = temp[x];
}
public static void Main(String[] args)
{
int [] arr = { -6, -3, -1, 2, 4, 5 };
int n = arr.Length;
Console.WriteLine( "Before sort " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
sortSquares(arr);
Console.WriteLine( "" );
Console.WriteLine( "After Sort " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function sortSquares(arr)
{
let n = arr.length;
let k;
for (k = 0; k < n; k++) {
if (arr[k] >= 0)
break ;
}
let i = k - 1;
let j = k;
let ind = 0;
let temp = new Array(n);
while (i >= 0 && j < n) {
if (arr[i] * arr[i] < arr[j] * arr[j]) {
temp[ind] = arr[i] * arr[i];
i--;
}
else {
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
while (i >= 0) {
temp[ind++] = arr[i] * arr[i];
i--;
}
while (j < n) {
temp[ind++] = arr[j] * arr[j];
j++;
}
for (let x = 0; x < n; x++)
arr[x] = temp[x];
}
let arr=[ -6, -3, -1, 2, 4, 5 ];
let n = arr.length;
document.write( "Before sort <br>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
sortSquares(arr);
document.write( "<br>" );
document.write( "After Sort <br>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
Python3
def sortSquares(arr, n):
K = 0
for K in range (n):
if (arr[K] > = 0 ):
break
i = K - 1
j = K
ind = 0
temp = [ 0 ] * n
while (i > = 0 and j < n):
if (arr[i] * arr[i] < arr[j] * arr[j]):
temp[ind] = arr[i] * arr[i]
i - = 1
else :
temp[ind] = arr[j] * arr[j]
j + = 1
ind + = 1
while (i > = 0 ):
temp[ind] = arr[i] * arr[i]
i - = 1
ind + = 1
while (j < n):
temp[ind] = arr[j] * arr[j]
j + = 1
ind + = 1
for i in range (n):
arr[i] = temp[i]
arr = [ - 6 , - 3 , - 1 , 2 , 4 , 5 ]
n = len (arr)
print ( "Before sort " )
for i in range (n):
print (arr[i], end = " " )
sortSquares(arr, n)
print ( "\nAfter Sort " )
for i in range (n):
print (arr[i], end = " " )
|
Output
Before sort
-6 -3 -1 2 4 5
After Sort
1 4 9 16 25 36
Time complexity: O(n)
Auxiliary Space: O(n)
Method 3:
Another efficient solution is based on the two-pointer method as the array is already sorted we can compare the first and last element to check which is bigger and proceed with the result.
Algorithm:
- Initialize left=0 and right=n-1
- if abs(left) >= abs(right) then store square(arr[left])
at the end of result array and increment left pointer
- else store square(arr[right]) in the result array and decrement right pointer
- decrement index of result array
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void sortSquares(vector< int >& arr, int n)
{
int left = 0, right = n - 1;
int result[n];
for ( int index = n - 1; index >= 0; index--) {
if ( abs (arr[left]) > arr[right]) {
result[index] = arr[left] * arr[left];
left++;
}
else {
result[index] = arr[right] * arr[right];
right--;
}
}
for ( int i = 0; i < n; i++)
arr[i] = result[i];
}
int main()
{
vector< int > arr;
arr.push_back(-6);
arr.push_back(-3);
arr.push_back(-1);
arr.push_back(2);
arr.push_back(4);
arr.push_back(5);
int n = 6;
cout << "Before sort " << endl;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
sortSquares(arr, n);
cout << endl;
cout << "After Sort " << endl;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG{
public static void sortSquares( int arr[])
{
int n = arr.length, left = 0 ,
right = n - 1 ;
int result[] = new int [n];
for ( int index = n - 1 ; index >= 0 ; index--)
{
if (Math.abs(arr[left]) > arr[right])
{
result[index] = arr[left] * arr[left];
left++;
}
else
{
result[index] = arr[right] * arr[right];
right--;
}
}
for ( int i = 0 ; i < n; i++)
arr[i] = result[i];
}
public static void main(String[] args)
{
int arr[] = { - 6 , - 3 , - 1 , 2 , 4 , 5 };
int n = arr.length;
System.out.println( "Before sort " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
sortSquares(arr);
System.out.println( "" );
System.out.println( "After Sort " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
C#
using System;
class GFG{
public static void sortSquares( int [] arr)
{
int n = arr.Length, left = 0,
right = n - 1;
int []result = new int [n];
for ( int index = n - 1;
index >= 0; index--)
{
if (Math.Abs(arr[left]) >
arr[right])
{
result[index] = arr[left] *
arr[left];
left++;
}
else
{
result[index] = arr[right] *
arr[right];
right--;
}
}
for ( int i = 0; i < n; i++)
arr[i] = result[i];
}
public static void Main( string [] args)
{
int []arr = {-6, -3, -1, 2, 4, 5};
int n = arr.Length;
Console.WriteLine( "Before sort " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
sortSquares(arr);
Console.WriteLine( "" );
Console.WriteLine( "After Sort " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function sortSquares(arr) {
let
n = nums.length,
left = 0,
right = n -1,
result = new Array(n)
;
for (let i = n - 1; i >= 0; i--) {
if (Math.abs(nums[left]) > Math.abs(nums[right])) {
result[i] = nums[left] ** 2;
left++;
} else {
result[i] = nums[right] **2;
right--;
}
}
return result;
}
let arr = [-6, -3, -1, 2, 4, 5];
let n = arr.length;
document.write( "Before sort " + "</br>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
sortSquares(arr);
document.write( "</br>" );
document.write( "After Sort " + "</br>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
Python3
def sortSquares(arr, n):
left, right = 0 , n - 1
index = n - 1
result = [ 0 for x in arr]
while index > = 0 :
if abs (arr[left]) > = abs (arr[right]):
result[index] = arr[left] * arr[left]
left + = 1
else :
result[index] = arr[right] * arr[right]
right - = 1
index - = 1
for i in range (n):
arr[i] = result[i]
arr = [ - 6 , - 3 , - 1 , 2 , 4 , 5 ]
n = len (arr)
print ( "Before sort " )
for i in range (n):
print (arr[i], end = " " )
sortSquares(arr, n)
print ( "\nAfter Sort " )
for i in range (n):
print (arr[i], end = " " )
|
Output
Before sort
-6 -3 -1 2 4 5
After Sort
1 4 9 16 25 36
Time complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...