VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-array-converting-elements-squares/

⇱ Sort array after converting elements to their squares - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort array after converting elements to their squares

Last Updated : 23 Jul, 2025

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  


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. 

  1. Divide the array into two-part "Negative and positive ".
  2. Use merge function to merge two sorted arrays into a single sorted array.

Below is the implementation of the above idea.


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:


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) 

Comment
Article Tags:
Article Tags: