Bubble Sort

Bubble Sort is one of the simplest sorting algorithms. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.

Although Bubble Sort is easy to understand and implement, it is not the most efficient sorting algorithm, especially for large datasets, as its time complexity is \(O(n^2)\) in the worst and average cases.


Algorithm

Here are the steps of the Bubble Sort algorithm:

  1. Start from the first element of the array.
  2. Compare the current element with the next element.
  3. If the current element is greater than the next element, swap them.
  4. Move to the next element and repeat steps 2 and 3 until the end of the array.
  5. Repeat steps 1 to 4 for all elements, reducing the range of comparison each time, as the largest elements are placed at the end of the array after each iteration.
  6. Stop when no swaps are needed, indicating that the array is sorted.

Example for Bubble Sort

Let’s sort the array [5, 3, 8, 4, 2] using Bubble Sort and explain each step:

Initial Array: