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

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.

Output:

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 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.

1. avinash

Yes, we can ignore the comparison here.

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