Sort array after converting elements to their squares | C ++ program to Sort square of the numbers of the array ; Function to sort an square array ; First convert each array elements into its square ; Sort an array using " sort ▁ STL ▁ function ▁ " ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE 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 << " After Sort " for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }