Bubble, insertion, selection
Use explicit passes to see how local swaps, a growing prefix, and suffix minima establish order.
Coding Patterns/Basics · B1
Use explicit passes to see how local swaps, a growing prefix, and suffix minima establish order.
Choose predictable stable merging or in-place partitioning when quadratic passes stop fitting the input size.
Use bounded key ranges or a small set of values to achieve linear work without general comparison sorting.
Runnable session
7 exercises · 49 named checks · Python 3 in your browser · saved locally
Implement bubble_sort(values). Return a new ascending list without mutating values. Use adjacent swaps and stop early when a complete pass makes no swaps; do not use sorted() or list.sort().
Each pass bubbles the largest remaining value to the end of the unsorted region.
An already-sorted input finishes after one swap-free pass.
Your code runs privately in the browser. Visible checks cover empty, boundary, and representative cases.
| Family | Core move | Time | Extra space | Stable |
|---|---|---|---|---|
| Bubble | Swap adjacent inversions | O(n²) | O(1) | Yes |
| Insertion | Grow a sorted prefix | O(n²) | O(1) | Yes |
| Selection | Select each suffix minimum | O(n²) | O(1) | No |
| Merge | Split, then stably merge | O(n log n) | O(n) | Yes |
| Quick | Partition around a pivot | O(n log n) avg. | O(log n) avg. | No |
| Counting | Count a bounded key range | O(n + k) | O(n + k) | Can be |
Read these constraints before writing a loop. They determine the invariant and the trade-off the interviewer will probe.
Prefer merge sort or a stable insertion. In a merge, take the left item first on equality.
Quicksort trades deterministic worst-case time for compact memory and strong average performance.
A small integer range or three categories can produce linear time without general comparison sorting.
Insertion sort adapts to existing order and can finish in linear time when no shifts are needed.