Hello everyone, Welcome back toProgramming In Python. Here in this post, I will continue with thealgorithm’s series, in previous posts I have discussed searching techniques likeLinear Search andBinary Search. Here I am going to say about a sorting technique called Bubble Sort. So let us start with the Bubble sort algorithm in Python.
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 YouTubehere
Bubble Sort Algorithm – Code Visualization
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.
- 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.
Ad:
Learn Python Programming Masterclass –Enroll Now.
Udemy
Program:
__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 otheralgorithmshere or some programs onlistshere or have a look atall the programs on Pythonhere.
Same algorithm in other programming languages
In C language: https://www.mycodingcorner.com/2014/12/c-program-for-sorting-elements-using.html
In CPP language: https://www.mycodingcorner.com/2015/03/cpp-program-for-sorting-elements-using-bubble-sort.html
In Java language: https://www.mycodingcorner.com/2015/01/java-bubble-sort.html