Bubble Sort
Bubble Sort is one of the most fundamental and simplest sorting algorithms. It works by repeatedly stepping through the list to be sorted, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated until the list is fully sorted.
The algorithm gets its name because smaller or larger elements "bubble" to the top or bottom of the list (depending on the sorting order) with each iteration, similar to air bubbles rising in water.
Video Explanation

How it Works:
- Start at the beginning: The algorithm begins at the first index of the array.
- Compare adjacent pairs: It compares the first element with the second element.
- Swap if necessary: If the first element is greater than the second (for ascending order), it swaps them.
- Move forward: It then moves to the next pair (second and third elements) and repeats the comparison and swap if necessary.
- Complete a pass: Once it reaches the end of the array, one "pass" is complete. The largest element will have "bubbled" up to its correct position at the end of the array.
- Repeat: The entire process is repeated for the remaining unsorted portion of the array until no swaps are made during a full pass, meaning the array is sorted.
Loading visualizer...
Time and Space Complexity:
- Best Case Time Complexity: This occurs when the array is already sorted. An optimized version of Bubble Sort can detect this in the first pass (by checking if any swaps were made) and terminate early.
- Average Case Time Complexity: On average, elements are randomly distributed, requiring multiple passes and swaps.
- Worst Case Time Complexity: This happens when the array is sorted in the reverse order. Every element needs to be swapped to the opposite end.
- Space Complexity: Bubble Sort is an in-place algorithm. It only requires a single extra memory space for the temporary variable used during swapping.
Step-by-Step Dry Run:
Let's sort the array [5, 1, 4, 2, 8] using Bubble Sort.
First Pass:
[5, 1, 4, 2, 8]Compare5and1.5 > 1, so swap. Array becomes[1, 5, 4, 2, 8][1, 5, 4, 2, 8]Compare5and4.5 > 4, so swap. Array becomes[1, 4, 5, 2, 8][1, 4, 5, 2, 8]Compare5and2.5 > 2, so swap. Array becomes[1, 4, 2, 5, 8][1, 4, 2, 5, 8]Compare5and8.5 < 8, so no swap. Array remains[1, 4, 2, 5, 8](At the end of the first pass, the largest element, 8, is at its correct sorted position at the end.)
Second Pass:
[1, 4, 2, 5, 8]Compare1and4.1 < 4, so no swap.[1, 4, 2, 5, 8]Compare4and2.4 > 2, so swap. Array becomes[1, 2, 4, 5, 8][1, 2, 4, 5, 8]Compare4and5.4 < 5, so no swap. (The last element 8 is already sorted, so we don't need to compare with it. The second largest element, 5, is now at its correct position.)
Third Pass:
[1, 2, 4, 5, 8]Compare1and2. No swap.[1, 2, 4, 5, 8]Compare2and4. No swap. (Since no swaps were made during this pass, the optimized algorithm knows the array is fully sorted and stops.)