
Sponsored
Sponsored
This approach utilizes the built-in sorting functionality available in most programming languages, which allows for custom sorting based on a key extracted from each element. The function fn is used to transform each element to its sorting key during the sort operation.
Time Complexity: O(n log n), where n is the length of the array, due to the sort operation.
Space Complexity: O(n), as sorted() creates a new list.
1function sortBy
JavaScript arrays possess a sort() method that can take a comparator function. By using the lambda (a, b) => fn(a) - fn(b), we derive the key values for comparison from the elements using fn.
This approach involves first creating a map of the computed keys from fn for all the elements in the array. These keys are then used to guide the sorting of the original array.
Time Complexity: O(n log n), owing to the sort operation.
Space Complexity: O(n), due to the additional storage in the form of key_map.
1def sort_by(arr, fn):
2 key_map = {x: fn(x) for x in arr}
3 arr.sort(key=lambda x: key_map[x])
4 return arr
5
6# Example usage
7arr = [5, 4, 1, 2, 3]
8fn = lambda x: x
9print(sort_by(arr, fn))key_map stores the result of applying fn to each element. The array is sorted based on look-up from this dictionary during the sorting phase, providing a precomputed sort key per element.