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
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