DSA Factory
Free Sorting lessonsSorting · Stage 1 · Comparing and swapping · Step 2

Pick the smallest, then move on

Each pass finds the smallest value left and swaps it to the front. About 8 minutes.

Find the smallest of what's left

Think of picking a team: each round you scan everyone still waiting and pick the best one. Pass number i looks only at positions i and after, because everything before is already settled from earlier passes.

Scan that stretch and remember the position of the smallest value you have seen so far, in a variable often called best.

Best starts at the first position: of the stretch, then updates whenever a smaller value turns up.
Track the position, not the value, so you know where to swap from.
Two passes over [5, 3, 8, 1, 9, 2]
1
0
3
1
8
2
5
3
9
4
2
5
ibest

Pass 1: the smallest value anywhere is 1, at index 3. Swap it to index 0.

Move 1 of 2

Swap it to the front, then move on

Once the scan ends, swap the smallest value into the first position of the stretch. That value is now settled for good, and the next pass never touches that position again. Then the start of the stretch moves forward by one.

Each pass does at most one swap, which is why this sort is gentle on writes.

One swap per pass, at most.
Best is already the start? The value was already in place, and the swap does nothing.
In code
n = len(nums)
for i in range(k):
    best = i
    for j in range(i + 1, n):
        if nums[j] < nums[best]:
            best = j
    tmp = nums[i]
    nums[i] = nums[best]
    nums[best] = tmp
return nums
Quick check

nums = [6, 2, 7, 1, 9]. What does nums look like after one pass of selection sort?

  1. A[1, 2, 7, 6, 9]
  2. B[1, 2, 6, 7, 9]
  3. C[6, 2, 7, 1, 9]
Show the answer

[1, 2, 7, 6, 9]. The smallest value anywhere is 1, at index 3. Swapping it with index 0 gives [1, 2, 7, 6, 9].

Your problem

After k passes

Selection sort works in passes. Pass i (starting at i = 0) scans nums from index i to the end, finds the smallest value in that stretch, and swaps it into index i. Return nums after exactly k passes (k = 0 means no passes at all).

Example
nums = [5, 3, 8, 1, 9, 2], k = 2 → [1, 2, 8, 5, 9, 3]

0 ≤ k ≤ n ≤ 100,000 · −1,000,000,000 ≤ each value ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve