Speed:
Insertion Sort
Best: O(n)Worst: O(n²)Stable & Adaptive
🃏How Insertion Sort Works
Insertion Sort builds the sorted array one element at a time by repeatedly taking an element from the unsorted portion and inserting it into its correct position in the sorted portion. It works similarly to how you might sort playing cards in your hands.
The algorithm divides the array into two parts:
- Sorted portion: Elements at the beginning (initially just the first element)
- Unsorted portion: Remaining elements to be processed
- For each element in the unsorted portion, find its correct position in the sorted portion
- Shift elements as needed and insert the current element
💻Implementation
📊Performance Analysis
Time Complexity
- • Best case: O(n) - already sorted
- • Average case: O(n²)
- • Worst case: O(n²) - reverse sorted
- • Space: O(1) in-place
Key Properties
- • Stable: maintains relative order
- • Adaptive: efficient for nearly sorted data
- • Online: can sort data as it arrives
- • In-place: requires only O(1) extra memory
🎯 Best Use Cases
- • Small datasets (typically n < 50)
- • Nearly sorted arrays
- • Online algorithms (data arrives over time)
- • Hybrid sorting (part of quicksort/mergesort)
- • Simple implementation needed
🔄 Compared to Other Sorts
- • vs Bubble Sort: More efficient, fewer swaps
- • vs Selection Sort: Adaptive, better for partial sorting
- • vs Quick Sort: Better for small arrays, stable
- • vs Merge Sort: In-place, but slower for large data