Fundamentals/Using Built-in Sort Functions
← PrevNext →
Sort an integer array in ascending order by delegating to the language's built-in sort function. Production code rarely hand-rolls a sort: built-in implementations run in O(n log n), are battle-tested, and handle edge cases for you. Your task is to wrap the built-in call in a function that returns a new sorted array without mutating the input.
If the language's default sort compares values lexicographically (so 100 sorts before 6), supply a numeric comparator so that integers are ordered by value rather than by string representation.
Input
arr: an array of integers (may be empty)
Output
A new array containing the same integers sorted in ascending order by numeric value.
Examples
Example 1
Inputarr = [3, 1, 4, 1, 5, 9]
Output[1, 1, 3, 4, 5, 9]
Explanation: The built-in sort orders the values from smallest to largest, preserving duplicates.
Example 2
Inputarr = [10, 20]
Output[10, 20]
Explanation: Already sorted input is returned unchanged.
Constraints
0 <= arr.length
Elements are integers.
The input array must not be mutated.
Use the language's built-in sort with a numeric comparator if needed.