![]() |
VOOZH | about |
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
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.
Below is the implementation of the above idea.
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:
Implementation:
Before sort -6 -3 -1 2 4 5 After Sort 1 4 9 16 25 36
Time complexity: O(n)
Auxiliary Space: O(n)