Learning Selection Sort in Python

What is Selection Sort?
Selection Sort is one of the simplest sorting algorithms in computer science. It works by repeatedly selecting the smallest element from the unsorted part of the list and moving it to the beginning. The list gets sorted one element at a time.
Here’s how it works:
Start from the first element and assume it’s the smallest.
Compare it with every other element in the list.
If you find a smaller one, update your smallest.
After scanning the rest of the list, swap the smallest with the current element.
Move to the next position and repeat the process until the entire list is sorted.
🧠 What I Learned
Selection Sort is simple but powerful for small lists.
The main idea is to find the minimum in each iteration and place it in the correct position.
You always move from left to right, sorting one element at a time.
The sorting is done in-place, so no extra memory is used.
✅ Python Code
Here’s the selection sort implementation I wrote and tested:
def selection_sort(arr):
n = len(arr)
for i in range(n):
smallest_element = i
for k in range(i+1, n):
if arr[k] < arr[smallest_element]:
smallest_element = k
arr[i], arr[smallest_element] = arr[smallest_element], arr[i]
return arr
arr = [5, 1, 2, 7, 0, 4]
print(selection_sort(arr))
🧪 Output
[0, 1, 2, 4, 5, 7]
🚀 Final Thoughts
Selection Sort helped me understand the basics of comparison-based sorting. While it's not the fastest for large datasets (O(n²) time complexity), it’s a great way to build foundational logic and understand how sorting works step by step.
Thanks for reading!
Subscribe to my newsletter
Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
