Algorithm Comparison
Race sorting algorithms against each other! See which algorithm performs best on different types of data.
Algorithm Race
Race Speed:100ms
When to Use Which Algorithm?
Bubble Sort
Only for educational purposes or very small arrays. Avoid in production.
Selection Sort
When memory writes are expensive. Makes minimum number of swaps.
Insertion Sort
Small arrays or nearly sorted data. Used in hybrid algorithms like Timsort.
Merge Sort
When stability is required. Great for linked lists and external sorting.
Quick Sort
General purpose. Fastest in practice for random data. Used in many libraries.
Heap Sort
When O(n log n) guarantee needed with O(1) space. Good for priority queues.
Performance Characteristics
Best for Sorted/Nearly Sorted Data
Insertion SortBubble Sort (optimized)
O(n) when data is almost sorted
Best for Random Data
Quick SortMerge Sort
O(n log n) average case
Best for Worst Case Guarantee
Merge SortHeap Sort
O(n log n) guaranteed
Best for Memory Efficiency
Heap SortQuick Sort
O(1) auxiliary space (or O(log n) for recursion)
Complete Complexity Comparison
| Algorithm | Best Time | Average Time | Worst Time | Space | Stable | Method |
|---|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n^2) | O(n^2) | O(1) | Yes | Exchanging |
| Selection Sort | O(n^2) | O(n^2) | O(n^2) | O(1) | No | Selection |
| Insertion Sort | O(n) | O(n^2) | O(n^2) | O(1) | Yes | Insertion |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes | Merging |
| Quick Sort | O(n log n) | O(n log n) | O(n^2) | O(log n) | No | Partitioning |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No | Selection |
Experiment Ideas
- 1.Try racing with a nearly sorted array - watch Insertion Sort shine!
- 2.Compare O(n^2) algorithms with O(n log n) - see the difference grow with array size
- 3.Race Quick Sort vs Merge Sort - which wins more often?
- 4.Watch the comparison and swap counts - efficiency isn't just about speed
- 5.Try reverse-sorted data - worst case for some algorithms
- 6.Compare Heap Sort vs Quick Sort - predictability vs speed