Sorting Simple sorts
143. Selection Sort
You are given an array of integers nums. Sort it in ascending order, smallest first, using selection sort.
Selection sort works in passes. Each pass finds the smallest value among the elements that are not yet in place, and swaps it to the front of them.
Change nums itself. The function returns nothing; the answer is what nums holds after it finishes. Every
copy of a repeated value stays, so equal values end up next to each other.
Write the sort yourself. Do not call your language's built-in sort, such as std::sort, Arrays.sort,
list.sort or Array.prototype.sort.
Example 1
Input: nums = [7, 3, 9, -2, 3]
[-2,3,3,7,9]Explanation: The first pass finds the smallest value, −2, and swaps it with the 7 at the front. Three more passes place the two 3s and then the 7, and the 9 is left last.
Example 2
Input: nums = [0, -12, 5, -1, 0]
[-12,-1,0,0,5]Explanation: Negative values come before 0, and the further below 0 a value is, the earlier it goes. The two 0s end up side by side.
Example 3
Input: nums = [3, 8, 11]
[3,8,11]Explanation: The array is already in order. Each pass finds its smallest value already at the front, so nothing moves.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 2000-109 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.