Bubble Sort Algorithm
In this lesson, we will learn about the bubble sort algorithm. We will also learn how to implement it in Python.
Last updated
In this lesson, we will learn about the bubble sort algorithm. We will also learn how to implement it in Python.
Last updated
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.
Suppose we are trying to sort the following list of numbers in ascending order:
First Iteration (Compare and Swap)
Starting from the first index, compare the first and the second elements.
If the first element is greater than the second element, swap them.
Now, compare the second and the third elements. Swap them if they are not in order.
The above process goes on until the last element
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.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct positions.
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