Question
Answer and Explanation
Sorting an integer array using a custom comparator allows you to define your own rules for ordering the elements. Here's how you can achieve this in various programming languages:
Java:
In Java, you can use the Arrays.sort()
method along with a custom Comparator
.
import java.util.Arrays;
import java.util.Comparator;
public class CustomSort {
public static void main(String[] args) {
Integer[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
// Custom comparison logic (e.g., descending order)
return b.compareTo(a); // Swap a and b for descending order
}
});
System.out.println(Arrays.toString(arr)); // Output: [9, 8, 5, 2, 1]
}
}
JavaScript:
In JavaScript, you can use the sort()
method with a custom compare function.
const arr = [5, 2, 8, 1, 9];
arr.sort(function(a, b) {
// Custom comparison logic (e.g., descending order)
return b - a; // Swap a and b for descending order
});
console.log(arr); // Output: [9, 8, 5, 2, 1]
Python:
In Python, you can use the sorted()
function or the sort()
method with a key
argument to specify a custom sorting function.
arr = [5, 2, 8, 1, 9]
# Using sorted()
sorted_arr = sorted(arr, reverse=True) # Descending order
print(sorted_arr) # Output: [9, 8, 5, 2, 1]
# Or, using arr.sort()
arr.sort(reverse=True) # Descending order
print(arr) # Output: [9, 8, 5, 2, 1]
C++:
In C++, you can use the std::sort()
function from the <algorithm>
header, along with a custom comparison function or lambda.
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> arr = {5, 2, 8, 1, 9};
std::sort(arr.begin(), arr.end(), [](int a, int b) {
// Custom comparison logic (e.g., descending order)
return a > b; // Swap comparison for descending order
});
for (int num : arr) {
std::cout << num << " "; // Output: 9 8 5 2 1
}
std::cout << std::endl;
return 0;
}
In each example, the key is to define a comparison function (or comparator) that takes two elements as input and returns a value indicating their relative order. A negative value means the first element should come before the second, a positive value means the first element should come after the second, and zero means they are equal.