Back to: Python Data Structure and Algorithims
Selection Sort in Python
Now that we understand the logic behind Selection Sort, let’s write the code to implement it.
We’ll use the same example list:
Step 1: Define the Function
We’ll create a function called selection_sort that takes a list as input:
Step 2: How the Code Works
-
Outer loop (
i): Goes through the list from index0tolen(list)-2.-
This loop represents the current position where we want to place the minimum element.
-
-
Set
min_index:-
Initially, we assume the first unsorted element is the minimum.
-
-
Inner loop (
j): Scans the rest of the list to find the true minimum.-
If a smaller value is found,
min_indexis updated.
-
-
Swap if necessary:
-
Only swap if the minimum index found is different from
i. -
This avoids unnecessary swaps when the current element is already the minimum.
-
-
Return sorted list.
Step 3: Run the Function
Output:
Step 4: Notes & Observations
-
After the first pass, the smallest element is in its correct position.
-
After the second pass, the second smallest element is in its correct position.
-
This continues until the entire list is sorted.
-
Time Complexity: O(n²) in all cases.
-
Space Complexity: O(1) (in-place sorting).