Square of a sorted array in C++

In the given array of sorted integers, the task is to print the squares of every array element and print the array in sorted order. For example,


arr[ ] = { -3,-1,0,1,4,6 };


{0,1,1,9,16, 36}

Explanation − The squares of each of the elements of the given array [-3, -1,0,1,4,6 ] is [0,1,1,9,16,36 ].


arr[ ]= { 0,1,2,8,9 }



Explanation − The squares of each of the elements of the given array [ 0,1,2,8,9 ] is [ 0,1,4,64,81 ].

Approach to solve this problem

To solve this particular problem, we can use the Two-Pointer approach. In Two-Pointer we use two pointers left and right. The left pointer initialized with the first element of the array and the right pointer points to the ending element of the array.

While iterating over the elements of the array we will find the square of the value and check whether the square of the right integer is greater or less than the left integer.

  • Take input an array of integers in increasing order.

  • An integer function squareAndSort(int *arr, int n) takes input as an array of integers and returns the square of each element of the array in a sorted manner.

  • Initialize two pointers left and right with the left element and rightmost element of the array.

  • Print the square of the element and compare it with the square of the right element.

  • Increment and decrement the left and right pointer accordingly.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
vector<int> squareAndSort(vector<int>&arr){
   int left= 0;
   int right= arr.size()-1;
      while(left <= right) {
         int v1 = arr[left]*arr[left];
         int v2 = arr[right]*arr[right];
         if(v1 <= v2) {
         else {
      reverse(vec.begin(), vec.end());
   return vec;
int main(){
   vector<int>arr= {-3,-1,0,1,4,6};
   vector<int>ans= squareAndSort(arr);
   for(auto x:ans){
      cout<<x<<" ";
   return 0;


Running the above code will generate the output as,

0 1 1 9 16 36

The square of each element of the array is, 9,1,0,1,16,36. After sorting these elements, the output will be 0 1 1 9 16 36.