Bubble Sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process continues until the list is fully sorted. While it's easy to understand, Bubble Sort is not very efficient for large datasets due to its quadratic time complexity. It’s often used for educational purposes or as a baseline for comparison with other sorting algorithms.
for i = 1 to (n - 1):
swapped = false
for j = 1 to (n - i):
if arr[j] < arr[j - 1]:
swap(j, j - 1)
swapped = true
if not swapped: break
Bubble Sort begins at the start of the array and compares the first two elements. If the first element is greater than the second, they are swapped. The algorithm then moves to the next pair and repeats the comparison. After one complete pass through the array, the largest element will have "bubbled up" to the last position. The algorithm then repeats the process for the remaining unsorted portion, ignoring the already-sorted elements at the end. This continues until no swaps are needed in a full pass, indicating the array is sorted.
Bubble Sort is primarily used as a teaching tool to introduce sorting concepts because of its simplicity. In practice, more efficient divide-and-conquer algorithms are preferred for large datasets. However, Bubble Sort can be useful for very small arrays or when the data is nearly sorted, as its optimized version achieves O(n) performance in the best case.
Metric / Operation | Complexity | Description |
|---|---|---|
| Best Case | O(n) | When the array is already sorted and the optimized version detects no swaps in the first pass. |
| Average Case | O(n²) | On average, each element must be compared with every other element. |
| Worst Case | O(n²) | When the array is sorted in reverse order, every possible swap must be performed. |
| Space Complexity | O(1) | Bubble Sort is an in-place algorithm that only requires a constant amount of additional memory for the swap variable. |
Hand-picked resources to deepen your understanding
© 2025 See Algorithms. Code licensed under MIT, content under CC BY-NC 4.0.