给定N个整数的数组arr [] ,任务是根据每个元素的立方对数组进行排序。
例子:
Input: arr[] = { 4, -1, 0, -5, 6 }
Output: -5 -1 0 4 6
Input: arr[] = { 12, 3, 0, 11 }
Output: 0 3 11 12
方法:想法是将Comparator函数与内置sort函数()结合使用,以根据其元素的多维数据集对数组进行排序。下面是使用的比较器函数:
bool comparator_function(int a, int b)
{
x = pow(a, 3);
y = pow(b, 3);
return x < y;
}
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Comparator function which returns
// a^3 is less than b^3
bool cmp(int a, int b)
{
int x = pow(a, 3);
int y = pow(b, 3);
return x < y;
}
// Function to sort the cubes of array
bool sortArr(int arr[], int n)
{
// Sort the array
sort(arr, arr + n, cmp);
// Print the array
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}
// Driver Code
int main()
{
// Given array
int arr[] = { 4, -1, 0, -5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
sortArr(arr, n);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
// Function to sort the cubes of array
static void sortArr(int arr[], int n)
{
Integer[] ar = new Integer[n];
for (int i = 0; i < n; i++)
ar[i] = arr[i];
// Sort the array
Arrays.sort(ar, new Comparator()
{
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;
}
});
// Print the array
for (int i = 0; i < n; i++)
{
System.out.print(ar[i] + " ");
}
}
// Driver code
public static void main(String[] args)
{
// Given array
int arr[] = { 4, -1, 0, -5, 6 };
int n = arr.length;
// Function Call
sortArr(arr, n);
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
# Function to sort the cubes of array
def sortArr(arr, n):
# Make a list of tuples in
# the form(cube of (num), num)
arr = [(i * i * i, i) for i in arr];
# Sort the array according to
# the their respective cubes
arr.sort()
# Print the array
for i in range(n):
print(arr[i][1], end = " ");
# Driver Code
if __name__ == "__main__" :
# Given array
arr = [ 4, -1, 0, -5, 6 ];
n = len(arr);
# Function Call
sortArr(arr, n);
# This code is contributed by AnkitRai01
C#
// C# program for the above approach
using System;
using System.Collections;
class compare : IComparer
{
// Call CaseInsensitiveComparer.Compare
public int Compare(Object x,
Object y)
{
return (
new CaseInsensitiveComparer()).Compare(x,y);
}
}
class GFG{
// Function to sort the cubes of array
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();
// Sort the array
Array.Sort(ar, cmp);
// Print the array
for (int i = 0; i < n; i++)
{
Console.Write(ar[i] + " ");
}
}
// Driver code
public static void Main(String[] args)
{
// Given array
int []arr = {4, -1, 0, -5, 6};
int n = arr.Length;
// Function Call
sortArr(arr, n);
}
}
// This code is contributed by gauravrajput1
输出:
-5 -1 0 4 6
时间复杂度: O(N * log N) ,其中N是数组中元素的数量。