Simple Sorts: Bubble and Selection
Sorting puts items in order, and it makes searching faster. Two simple methods:
- Bubble sort walks the list, swapping neighbours that are out of order. After each pass the largest unsorted item has "bubbled" to the end.
- Selection sort finds the smallest remaining item and swaps it into the next position.
Both use nested loops, so both are O(n squared): fine for a few dozen items, painfully slow for thousands. They are worth learning because they are easy to understand.
Examplepython
Quick check
What is the Big O of bubble sort?
Your turn: write the code
Do ONE pass of bubble sort (swap every out-of-order neighbour pair once, left to right) and print the list.
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.