Bubble Sort Algorithm

In this lesson, we will learn about the bubble sort algorithm. We will also learn how to implement it in Python.

Bubble sort is an algorithm that compares adjacent elements in a list and swaps them if they are out of order. It continues to do this until the list is sorted. The algorithm is named bubble sort because the largest element in the list "bubbles" to the top of the list.

Just like the movement of air bubbles in water that rise to the top, the largest element in the list will bubble to the top. The algorithm will then ignore the largest element and repeat the process until the list is sorted.

Working of the Bubble Sort Algorithm

Suppose we are trying to sort the following list of numbers in ascending order:

[5, 1, 4, 2, 8]
  1. First Iteration (Compare and Swap)

    1. Starting from the first index, compare the first and the second elements.

    2. If the first element is greater than the second element, swap them.

    3. Now, compare the second and the third elements. Swap them if they are not in order.

    4. The above process goes on until the last element

Compare the Adjacent Elements
  1. Remaining Iteration

The same process goes on for the remaining iterations.

After each iteration, the largest element among the unsorted elements is placed at the end.

Put the largest element at the end

In each iteration, the comparison takes place up to the last unsorted element.

Compare the adjacent elements

The array is sorted when all the unsorted elements are placed at their correct positions.

The array is sorted if all elements are kept in the right order

Bubble Sort Algorithm

Bubble Sort Code in Python

Optimized Bubble Sort Algorithm

In the above algorithm, all the comparisons are made even if the array is already sorted. This increases the execution time.

To solve this, we can introduce an extra variable swapped. The value of swapped is set true if there occurs swapping of elements. Otherwise, it is set false.

After an iteration, if there is no swapping, the value of swapped will be false. This means elements are already sorted and there is no need to perform further iterations.

This will reduce the execution time and helps to optimize the bubble sort.

Algorithm for optimized bubble sort is

Optimized Bubble Sort in Python

Last updated

Was this helpful?