selection sort
Selection sort is a comparison-based sorting algorithm that repeatedly selects the smallest remaining value and moves it into its final position, growing a sorted run one element at a time.
The algorithm treats a list as two parts, a sorted portion at the front and an unsorted portion behind it. On each pass, it scans the whole unsorted portion to find the minimum value, swaps that value into the first unsorted slot, and advances the boundary by one. It repeats until nothing unsorted remains.
Step through a full sort in the visualizer below to watch each pass scan the unsorted portion, lock its smallest value into the sorted run, and advance the boundary one slot at a time:
Because each pass scans every remaining element no matter how the values are arranged, selection sort does the same amount of work on sorted, random, and reversed input. Its time complexity is O(n^2) in the best, average, and worst cases, which rules it out for large collections. A few traits still set it apart from other sorting algorithms:
- Few writes: It performs at most
n - 1swaps, the fewest among the simple quadratic sorts, which helps when writing to storage is expensive. - In place: It rearranges the data within the original list, so its space complexity is
O(1). - Unstable: A swap can move an element past an equal one, so the prior order of equal keys is not preserved.
Selection sort is mostly of teaching value today, since its short, order-independent logic is quick to trace by hand. Python’s built-in sorted() and list.sort() rely on Timsort, which adapts to existing order and runs far faster on real data.
Related Resources
Tutorial
Sorting Algorithms in Python
In this tutorial, you'll learn all about five different sorting algorithms in Python from both a theoretical and a practical standpoint. You'll also learn several related and important concepts, including Big O notation and recursion.
For additional information on related topics, take a look at the following resources:
- Introduction to Sorting Algorithms in Python (Course)
- How to Do a Binary Search in Python (Tutorial)
- Linked Lists in Python: An Introduction (Tutorial)
- Lists vs Tuples in Python (Tutorial)
- Creating a Binary Search in Python (Course)
- Working With Linked Lists in Python (Course)
- Linked Lists in Python: An Introduction (Quiz)
- Lists and Tuples in Python (Course)
- Lists vs Tuples in Python (Quiz)
By Martin Breuss • Updated Aug. 7, 2026