CodeBlanks Logo Icon CodeBlanks

Finding the minimum

Find the index of the minimum in a slice.

Swapping

Once the minimum is found, you swap it with the first element of the unsorted part. This places that element in its correct position.

Swapping takes O(1) time: only two elements are exchanged. In total, n-1 swaps are performed.

Sorted part growth

After each swap, the sorted part grows by one element. Selection sort expands the sorted part from the start to the end.

At step i, the first i elements are sorted and the rest are unsorted. At the last step, the whole array is sorted.

Practice Swap elements

Write swap_min(arr, i, min_idx). Swap arr[i] and arr[min_idx], return arr. Print [1, 3, 2] with print(swap_min([3, 1, 2], 0, 1)).

Starter code

solution.py
def swap_min(arr, i, min_idx):
    # Swap two elements

Sample solution

solution.py
def swap_min(arr, i, min_idx):
    # Swap two elements
    arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr
print(swap_min([3, 1, 2], 0, 1))

Expected output

[1, 3, 2]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Swap

Question
Swap two elements: arr[i], arr[min_idx] = ____
Answer
Swap two elements: arr[i], arr[min_idx] = arr[min_idx]

Explanation: arr[min_idx] is right.

2 Finding the minimum: match the terms

Term Meaning
Swap Exchange
min_idx Minimum index
O(1) Swap time
n-1 Swap count

3 How long does a swap take?

  • O(log n) Correct answer
  • O(n^2)
  • O(n)
  • O(1)

Explanation: A swap is O(1).

All lessons in Beginner