DEV Community

Shahriyar Al Mustakim Mitul
Shahriyar Al Mustakim Mitul

Posted on

DSA by Mitul in C++, Python, and Java : Bubble sort

Bubble sort (Sinking sort)

We repeatedly compare adjacent values and swap if is in an incorrect order.
So, here you can see some values which needs to be sorted. First we will compare 1st 2 values ,

Image description

Here 5<9 thus we will not swap. Let's move to the next pair then.

Image description
As 9>3, thus it will swap

Image description
Again move to the next pair

Image description
As 9>1, so swap them.

Image description

This process will go untill the last element.
So, after complete iteration the biggest value will move to the right

Image description
Let's start the 2nd iteration:

Image description
After the 2nd iteration 8 & 9 will be sorted

Image description
After 3rd iteration we will have:

Image description
After 4th,

Image description
This process will continue and finally we will have:

Image description

All sorted in the ascending order.
Code for Bubble sort:

def bubbleSort(customList):
    for i in range(len(customList)-1):
        for j in range(len(customList)-i-1):
            if customList[j] > customList[j+1]:
                customList[j], customList[j+1] = customList[j+1], customList[j]
    print(customList)
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Image description

When to use Bubble Sort?

  1. When the input is already sorted.
  2. Space is a concern.
  3. Easy to implement.

When to avoid Bubble Sort?
Average time complexity is poor.

Top comments (0)