Fundamentals/Selection Sort
← PrevNext →
Implement selection sort to sort an integer array in ascending order. The algorithm divides the array into a sorted prefix and an unsorted suffix. On each pass, scan the unsorted portion to find the index of the smallest remaining element, then swap that element into the boundary position. After n-1 passes, the array is fully sorted.
Return a new sorted array; do not mutate the input.
Input
arr: an array of integers (may be empty)
Output
A new array containing the same integers sorted in ascending order.
Examples
Example 1
Inputarr = [5, 2, 8, 1, 4]
Output[1, 2, 4, 5, 8]
Explanation: Each pass selects the next smallest value and places it at the current boundary.
Example 2
Inputarr = [64, 25, 12, 22, 11]
Output[11, 12, 22, 25, 64]
Explanation: 11 is selected first, then 12, then 22, and so on.
Constraints
0 <= arr.length
Elements are integers.
The input array must not be mutated.
Use the selection sort algorithm.