Here's how it works: The algorithm makes multiple passes through the array. In each pass, it compares each pair of adjacent elements and swaps them if the first is greater than the second (for ascending order). After the first pass, the largest element will have "bubbled up" to its correct position at the end of the array. The process continues, with each subsequent pass placing the next largest element in its correct position.
For example, if we're sorting [5, 3, 8, 2], the first pass would compare 5 and 3 (swap to get [3, 5, 8, 2]), then 5 and 8 (no swap), then 8 and 2 (swap to get [3, 5, 2, 8]). After this first pass, 8 is in its final position. The algorithm continues until no more swaps are needed.
The time complexity of bubble sort is O(n²) in the worst and average cases, where n is the number of elements. In the best case, when the array is already sorted, it can achieve O(n) if implemented with an optimization that stops when no swaps occur in a pass. The space complexity is O(1) since it sorts in-place.
While bubble sort is inefficient for large datasets compared to algorithms like quicksort or mergesort, it has some advantages: it's simple to understand and implement, it's stable (maintains the relative order of equal elements), and it can detect if the list is already sorted efficiently with the right optimization. It's primarily used for educational purposes or for very small datasets where its simplicity outweighs its inefficiency.