Algorithm


Bubble Sort Algorithm:

  1. Start with an unsorted array.
  2. Repeat the following steps until no swaps are needed:
    1. Traverse the array from the first element to the second-to-last element.
    2. Compare each pair of adjacent elements.
    3. If the first element is greater than the second, swap them.
  3. If no swaps occur during a pass, the array is already sorted and the algorithm terminates.
  4. Otherwise, repeat the process for the remaining unsorted portion of the array.

Example:

Bubble Sort Example

Fig. 1: Step-by-Step Process for One Iteration

Bubble Sort Example

Fig. 2: Iteration by Iteration Visualization of Bubble sort

Note: Bubble Sort ensures that the largest unsorted element "bubbles" to its correct position after each pass.