3️⃣

16.3 Selection Sort - Code Breakdown

Selection Sort - Code Breakdown

I’m going to give the code first, then we will explain it:

arr = [1, 4, 2, 7, 7, 6]  # change this array to the array you want to sort
for first_idx in range(len(arr)):
    min_idx = first_idx
    for second_idx in range(first_idx + 1, len(arr)):
        if arr[second_idx] < arr[min_idx]:
            min_idx = second_idx
    arr[first_idx], arr[min_idx] = arr[min_idx], arr[first_idx]

print(arr)

View code on GitHub.

Line 1 is the sample list.

Line 2 is going to loop through each element in the list and first_idx is the index that will contain the smallest element after being swapped. This index increases with every iteration.

Line 3 is going to store the minimum value (in min_idx) as we loop through everything starting from first_idx +1 (not starting from first_idx because we know the element at first_idx can’t be smaller than itself).

Line 4-6 is going to loop through each element starting from first_idx +1 and locate the smallest element to be swapped with first_idx. This element’s index will be put in min_idx.

Line 7 is going to use the tuple unpacking to swap the element at first_idx with the element at min_idx (which contains the minimum element starting from first_idx).

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.