In this tutorial, you will learn the bubble sort algorithm. Also, you will find working examples of `bubble sort algorithm` in Python.

#### What is Bubble Sort Algorithm?

Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. `Bubble sort` algorithm is not suitable for large data sets as its average and worst-case complexity are of Ο(n2) where n is the number of items. The order can be ascending or descending.

#### How does Bubble Sort work?

1. Starting from the first index, compare the first and the second elements. If the first element is greater than the second element, they are swapped. Now, compare the second and third elements. Swap them if they are not in order. The above process goes on until the last element.
2. 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.

#### Optimized Bubble Sort

In the above code, all possible comparisons are made even if the array is already sorted. It increases the execution time. The code can be optimized by introducing an extra variable swapped. After each iteration, if there is no swapping taking place then, there is no need for performing further loops.

In such a case, the variable swapped is set false. Thus, we can prevent further iterations. The algorithm for optimized bubble sort is

#### Complexity

Bubble Sort is one of the simplest sorting algorithms. Two loops are implemented in the algorithm.

Cycle Number of Comparisons
1st (n-1)
2nd (n-2)
3rd (n-3)
……. ……
last 1

Number of comparisons: (n – 1) + (n – 2) + (n – 3) +…..+ 1 = n(n – 1) / 2 nearly equals to n2
Complexity: O(n2)
Also, we can analyze the complexity by simply observing the number of loops. There are 2 loops so the complexity is `n*n = n2`

#### Time Complexities:

• Worst Case Complexity: O(n2)
If we want to sort in ascending order and the array is in descending order then, the worst case occurs.
• Best Case Complexity: O(n)
If the array is already sorted, then there is no need for sorting.
• Average Case Complexity: O(n2)
It occurs when the elements of the array are in jumbled order (neither ascending nor descending).

#### Space Complexity:

Space complexity is O(1) because an extra variable temp is used for swapping. In the optimized algorithm, the variable swapped adds to the space complexity thus, making it O(2).

The article was published on November 25, 2020 @ 12:47 PM