Explain Bubble Sort with the help of example.


Q.) Explain Bubble Sort with the help of example.

Subject: Data Structures

Bubble Sort is a simple comparison-based sorting algorithm. It is named so because it bubbles up the largest or smallest element to its correct position in each iteration. It is best suited for small lists or for lists that are already or nearly sorted.

Here's how Bubble Sort works:

  1. Compare the first and second elements of the list. If the first element is greater than the second element, they are swapped.
  2. The process is repeated for the second and third elements, and so on, until the end of the list. This completes the first pass, and the largest element is now at the end of the list.
  3. Repeat the process for the list, but now the last element is not included as it is already sorted. This is the second pass.
  4. Repeat the process until no more swaps are needed.

Let's illustrate this with an example. Suppose we have the following list of numbers:

[5, 3, 8, 4, 2]

Pass List Swapped Elements
1 [5, 3, 8, 4, 2] (5,3)
1 [3, 5, 8, 4, 2] (5,4)
1 [3, 4, 8, 5, 2] (5,2)
1 [3, 4, 5, 8, 2] (8,2)
1 [3, 4, 5, 2, 8] -
2 [3, 4, 5, 2, 8] (4,2)
2 [3, 2, 5, 4, 8] (5,4)
2 [3, 2, 4, 5, 8] -
3 [3, 2, 4, 5, 8] (3,2)
3 [2, 3, 4, 5, 8] -

As you can see, after each pass, the largest element is moved to its correct position. The process is repeated until the list is sorted.

The time complexity of Bubble Sort is O(n^2) in the worst case when the list is reverse sorted, and O(n) in the best case when the list is already sorted. The space complexity is O(1), as only a single additional memory space is required.

Bubble Sort is not suitable for large data sets as its average and worst-case complexity are high. It is used when memory space is a primary concern.