Bubble Sort algorithm in Python

Hello everyone, Welcome back to programminginpython.com. Here in this post, I will continue with the algorithm’s series, in previous posts I have discussed searching techniques like Linear Search and Binary Search, here I am going to say about a sorting technique called Bubble Sort.

Bubble Sort is one of the simple sorting techniques where it traverses the whole list by comparing its adjacent elements, sorting them, and swapping the elements until the whole list is sorted.

You can also watch the video on YouTube here

Bubble Sort Algorithm – Code Visualization

Program on Github

Time Complexity of Bubble Sort

Best CaseO(n)
Average CaseO(n2)
Worst CaseO(n2)


Given a list L of n elements with values or records L0, L1, …, Ln-1, bubble sort is applied to sort the list L.

  1. Compare the first two elements L0, L1 on the list.
  2. if L1 < L0, swap those elements and continue with the next 2 elements.
  3. Repeat the same step until whole the list is sorted, so no more swaps are possible.
  4. Return the final sorted list.

Program on Github



Bubble Sort Algorithm - programminginpython.com
Bubble Sort Algorithm – programminginpython.com
Bubble Sort Algorithm - programminginpython.com
Bubble Sort Algorithm – programminginpython.com

Program on Github

Feel free to look at some other algorithms here or some programs on lists here or have a look at all the programs on python here.

Same algorithm in other programming languages

In C languagehttp://www.mycodingcorner.com/2014/12/c-program-for-sorting-elements-using.html

In CPP languagehttp://www.mycodingcorner.com/2015/03/cpp-program-for-sorting-elements-using-bubble-sort.html

In Java languagehttp://www.mycodingcorner.com/2015/01/java-bubble-sort.html


  1. Eric Saper

    Avinash, one thing: with the first iteration of the outer for loop, the largest value is pushed to the end of the list. After each subsequent iteration, the next largest remaining value ends up just before the previous one. Therefore, there is no need to compare the values at the end of the list again on subsequent iterations.

    The loops should be written as:
    for j in range(len(sort_list) – 1):
    for k in range(len(sort_list) – j – 1):

    This will considerably improve performance.

  2. Pingback: Bubble Sort Merge Sort and Quick Sort in Python – Vegibit

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.