Sorting Algorithm Visualizer
Visualize how different sorting algorithms organize data step-by-step.
Visualization
Bubble Sort
A simple comparison-based algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Time Complexity
O(n²)
Space Complexity
O(1)
Stability
Stable
Controls
How Bubble Sort Works
Bubble Sort repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
- Start at the beginning of the array
- Compare the first two elements
- If the first is greater than the second, swap them
- Move to the next pair of elements and repeat
- After each pass, the largest element "bubbles" to the end
- Repeat until the array is sorted
Algorithm Comparison
Algorithm | Best | Average | Worst | Space | Stable |
---|---|---|---|---|---|
Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
When to Use Different Sorting Algorithms
Small Data Sets
For very small arrays (fewer than 20 elements), simple algorithms like Insertion Sort often outperform complex ones due to lower overhead.
Nearly Sorted Data
When data is already partially sorted, Insertion Sort can be very efficient with O(n) time complexity.
Limited Memory
In memory-constrained environments, Selection Sort or Insertion Sort with O(1) space complexity might be preferred.
Stable Sorting Needed
When you need to preserve the relative order of equal elements, choose Merge Sort or Bubble Sort.
General Purpose
For most applications with moderate to large data sets, Quick Sort is often the algorithm of choice due to its efficiency.
Guaranteed Performance
When you need guaranteed O(n log n) worst-case performance, Merge Sort is preferable to Quick Sort.
Coming Next
Stay tuned for more algorithm visualizations, including pathfinding algorithms, dynamic programming, and more complex data structures!
Back to Algorithm Visualizers