Elementary Sorting Algorithms: Bubble, Selection & Insertion Sort (O(n²))
Elementary Sorting Algorithms: Bubble, Selection & Insertion Sort (O(n²))
Sorting rearranges elements in a sequence into monotonic ascending or descending order. While advanced algorithms (Merge Sort, Quick Sort) dominate big data, understanding the elementary trio—Bubble Sort, Selection Sort, and Insertion Sort—is critical for mastering algorithmic trade-offs, stability, and small-data optimizations.
1. Real-World Analogies
- Bubble Sort (Fizzy Soda): Heavy elements sink to the bottom while lighter elements bubble up to the surface one-by-one through adjacent pairwise swaps.
- Selection Sort (Picking the MVP): You scan the entire crowd, select the absolute shortest person, and place them at index 0. Then scan the remainder, find the next shortest, and place them at index 1.
- Insertion Sort (Arranging Playing Cards): You hold cards in your hand. As you pick up each new card from the deck, you slide it into its correct sorted position among the cards already in your hand.
2. The Big-O Comparison Table
| Algorithm | Best Time | Average Time | Worst Time | Space | Stable? | Adaptive? |
|---|---|---|---|---|---|---|
| Bubble Sort | $O(n)$ (with flag) | $O(n^2)$ | $O(n^2)$ | $O(1)$ | Yes | Yes |
| Selection Sort | $O(n^2)$ | $O(n^2)$ | $O(n^2)$ | $O(1)$ | No | No |
| Insertion Sort | $O(n)$ | $O(n^2)$ | $O(n^2)$ | $O(1)$ | Yes | Yes |
Note: An algorithm is Stable if equal elements preserve their original relative order after sorting.
3. Algorithm 1: Optimized Bubble Sort ($O(n)$ Best Case)
4. Algorithm 2: Selection Sort (Minimizing Memory Writes)
Selection Sort performs at most $n$ total swaps, making it useful when writing to flash memory where write operations are costly:
5. Algorithm 3: Insertion Sort (King of Nearly-Sorted Data)
Insertion Sort is blazing fast for small arrays ($n \le 30$) or nearly-sorted data. Production algorithms like Timsort (used in Python sorted() and Java Arrays.sort()) use Insertion Sort as their base-case engine!
Modern JavaScript / TypeScript Implementation:
6. Trace Table: Insertion Sort on [5, 2, 4, 6, 1]
| Pass ($i$) | Key | Subarray before insertion | Comparisons & Shifts | Subarray after pass |
|---|---|---|---|---|
| 1 | 2 | [5] | 5 > 2 $\to$ shift 5 right | [2, 5, 4, 6, 1] |
| 2 | 4 | [2, 5] | 5 > 4 $\to$ shift 5 right | [2, 4, 5, 6, 1] |
| 3 | 6 | [2, 4, 5] | 5 < 6 $\to$ 0 shifts | [2, 4, 5, 6, 1] |
| 4 | 1 | [2, 4, 5, 6] | Shift 6, 5, 4, 2 right | [1, 2, 4, 5, 6] |
Multiple Choice Questions
Merge Sort: Divide-and-Conquer Paradigm & Stability Analysis
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.