For any queries you can reach us at / WhatsApp us: +919158876092

Bubble Sort in Data Structures - Infovistar

Bubble Sort

The bubble sort is one of the simplest and most popular sorting algorithms.

The bubble sort works by repeatedly swapping adjacent elements until they are no longer in the intended order.

It is called bubble sort because it mimics the movement of bubbles in water.

A bubble in water rises to the surface each time; similarly, elements in the bubble sort are moved to the end in each iteration.

Although simple to use, bubble sort is mainly used as an educational tool because its performance is poor in the real world.

It is not suitable for large data sets.

The average and worst-case complexity of Bubble sort is O (n2), where n is a number of items.

Time Complexity

Case Time Complexity
Best Case O(n)
Average Case O(n2)
Worst Case O(n2)
  • Best Case O(1):It occurs when there is no sorting needed, i.e. the array is already sorted.
  • Average Case O(n): The array elements are in a jumbled order that is not properly ascending and descending.
  • Worst Case O(n): This occurs when the array elements need to be sorted in reverse order. In other words, suppose you have to sort an array in ascending order, but its elements are arranged in descending order.

Space Complexity

Space Complexity O(1)
Stable Yes
  • A bubble sort required extra variables for swapping. Hence, the space complexity of bubble sorting is O(1).
  • The space complexity of optimized bubble sort is O(2). It is because two extra variables are required in optimized bubble sort.

Bubble Sort