Given an array arr and a function fn, return a sorted array sortedArr.
You can assume fn only returns numbers and those numbers determine the sort order of sortedArr. sortedArr must be sorted in ascending order by
fn output.
You may assume that fn will never duplicate numbers for a given array.
Input: arr =[5,4,1,2,3], fn =(x)=> x
Output:[1,2,3,4,5] Explanation: fn simply returns the number passed to it so the array is sorted in ascending order.
Input: arr =[{"x":1},{"x":0},{"x":-1}], fn =(d)=> d.x Output:[{"x":-1},{"x":0},{"x":1}] Explanation: fn returns the value for the "x" key. So the array is sorted based on that value.
Method 1 - Using Array.sort() with Custom Comparator#
Intuition: Use JavaScript’s built-in sort() method with a custom comparator function that applies the given function fn to each element and compares the results.
Approach:
Use the sort() method with a comparator function
For each pair of elements, apply the function fn to get their sort keys
import java.util.*;
import java.util.function.Function;
publicclassSolution {
publicstatic<T> List<T>sortBy(List<T> arr, Function<T, Integer> fn) {
List<T> result =new ArrayList<>(arr);
result.sort(Comparator.comparing(fn));
return result;
}
// Example usagepublicstaticvoidmain(String[] args) {
// Sort integers by their value List<Integer> nums = Arrays.asList(5, 4, 1, 2, 3);
List<Integer> sortedNums = sortBy(nums, x -> x);
// Sort strings by their length List<String> words = Arrays.asList("hello", "hi", "world");
List<String> sortedWords = sortBy(words, String::length);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fun <T> sortBy(arr: List<T>, fn: (T) -> Int): List<T> {
return arr.sortedBy { fn(it) }
}
// Example usage
funmain() {
// Sort integers by their value
val nums = listOf(5, 4, 1, 2, 3)
val sortedNums = sortBy(nums) { it }
// Sort strings by their length
val words = listOf("hello", "hi", "world")
val sortedWords = sortBy(words) { it.length }
}
defsort_by(arr, fn):
"""
Sort array by applying function fn to each element.
Args:
arr: List of elements to sort
fn: Function that takes an element and returns a number for sorting
Returns:
Sorted list in ascending order by fn output
"""return sorted(arr, key=fn)
# Example usageif __name__ =="__main__":
# Sort numbers by their value nums = [5, 4, 1, 2, 3]
sorted_nums = sort_by(nums, lambda x: x)
# Sort dictionaries by 'x' key dicts = [{"x": 1}, {"x": 0}, {"x": -1}]
sorted_dicts = sort_by(dicts, lambda d: d["x"])
# Sort arrays by second element arrays = [[3, 4], [5, 2], [10, 1]]
sorted_arrays = sort_by(arrays, lambda x: x[1])