Sort squares of a sorted array in one pass

To sort squares of a sorted array, you don’t want to use any sorting algorithms such as bubble sort. Because it takes O(nlogn) ~ O(n^2) time. Here we introduce a better way to sort in one pass.

sort square

The solution is using two pointers. Initialize two pointers, one points to the first element, and the other points to the last element. Then compare the absolute value of these two elements pointed by the indices. Put the square of the larger one at the end of the output array. Then increase or decrease the larger one’s index. When all the elements have been compared, the output is the sorted square. With the optimized version of sort squares of a sorted array, the solution has the time complexity to O(n).

Question statement:
Input: sorted integers: example: [-2, 1, 2, 3]
Output: sorted squares of the input: [1, 4, 4 ,9]

Java

JavaScript

Python

Output:
Input array: [-2, 1, 2, 3]
Sorted squares: [1, 4, 4, 9]

O Notation:
Time complexity: O(n)
Space complexity: O(n)

How to sort squares of a sorted array?

Given a sorted array, return the squares of each element in the array and the squares are sorted. You don’t need sorting algorithm. Instead you use two pointers, one points to the first element, and the other points to the last element. Then compare the squares of these two elements pointed by the indices. Put the square of the larger one at the end of the output array.


Download SortSquares.java
Download SortSquares.js
Download SortSquares.py

Comments are closed