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 technique 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 Case O(n)
Average Case O(n2)
Worst Case O(n2)

Algorithm:

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 first two elements L0, L1 in the list.
  2. if L1 < L0, swap those elements and continue with 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

Program:

Output:

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

Leave a Reply