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

#### Time Complexity of Bubble Sort

Best Case |
O(n) |

Average Case |
O(n^{2}) |

Worst Case |
O(n^{2}) |

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

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

#### Program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
__author__ = 'Avinash' def bubble_sort(sort_list): for j in range(len(sort_list)): for k in range(len(sort_list) - 1): if sort_list[k] > sort_list[k + 1]: sort_list[k], sort_list[k + 1] = sort_list[k + 1], sort_list[k] print(sort_list) lst = [] size = int(input("Enter size of the list: \t")) for i in range(size): elements = int(input("Enter the element: \t")) lst.append(elements) bubble_sort(lst) |

#### 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 C language**: http://www.mycodingcorner.com/2014/12/c-program-for-sorting-elements-using.html

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

**In Java language**: http://www.mycodingcorner.com/2015/01/java-bubble-sort.html

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.

Yes, we can ignore the comparison here.

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