Sort the array according to their cubes of each element
Given an array arr[] of N integers, the task is to sort the array according to the cubes of each element.
Examples:
Input: arr[] = { 4, -1, 0, -5, 6 }
Output: -5 -1 0 4 6
Input: arr[] = { 12, 3, 0, 11 }
Output: 0 3 11 12
Approach: The idea is to use the Comparator function with an inbuilt sort function() to sort the array according to the cubes of its elements. Below is the comparator function used:
bool comparator_function(int a, int b)
{
x = pow(a, 3);
y = pow(b, 3);
return x < y;
}
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool cmp( int a, int b)
{
int x = pow (a, 3);
int y = pow (b, 3);
return x < y;
}
bool sortArr( int arr[], int n)
{
sort(arr, arr + n, cmp);
for ( int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
}
int main()
{
int arr[] = { 4, -1, 0, -5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
sortArr(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void sortArr( int arr[], int n)
{
Integer[] ar = new Integer[n];
for ( int i = 0 ; i < n; i++)
ar[i] = arr[i];
Arrays.sort(ar, new Comparator<Integer>()
{
public int compare(Integer a, Integer b)
{
int x = ( int )Math.pow(a, 3 );
int y = ( int )Math.pow(b, 3 );
return (x < y) ? - 1 : 1 ;
}
});
for ( int i = 0 ; i < n; i++)
{
System.out.print(ar[i] + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 4 , - 1 , 0 , - 5 , 6 };
int n = arr.length;
sortArr(arr, n);
}
}
|
Python3
def sortArr(arr, n):
arr = [(i * i * i, i) for i in arr];
arr.sort()
for i in range (n):
print (arr[i][ 1 ], end = " " );
if __name__ = = "__main__" :
arr = [ 4 , - 1 , 0 , - 5 , 6 ];
n = len (arr);
sortArr(arr, n);
|
C#
using System;
using System.Collections;
class compare : IComparer
{
public int Compare(Object x,
Object y)
{
return (
new CaseInsensitiveComparer()).Compare(x,y);
}
}
class GFG{
static void sortArr( int []arr,
int n)
{
int [] ar = new int [n];
for ( int i = 0; i < n; i++)
ar[i] = arr[i];
IComparer cmp = new compare();
Array.Sort(ar, cmp);
for ( int i = 0; i < n; i++)
{
Console.Write(ar[i] + " " );
}
}
public static void Main(String[] args)
{
int []arr = {4, -1, 0, -5, 6};
int n = arr.Length;
sortArr(arr, n);
}
}
|
Javascript
<script>
function sortArr(arr, n)
{
arr.sort( function ( a , b){
var x = Math.pow(a,3);
var y = Math.pow(b,3);
if (x > y) return 1;
if (x < y) return -1;
return 0;
});
for ( var i = 0; i < n; i++) {
document.write(arr[i] + " " );
}
}
var arr = [ 4, -1, 0, -5, 6 ];
var n = arr.length;
sortArr(arr, n);
</script>
|
Time Complexity: O(N*log N), where N is the number of elements in the array.
Space Complexity : O(1) , as it only uses a constant amount of extra memory to sort the array and print the result
Last Updated :
31 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...