Home » Bubble Sort algorithm in Python

Bubble Sort algorithm in Python

Bubble Sort algorithm in Python

Hello everyone, Welcome back to Programming In Python. 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. 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 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 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

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:

Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python

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 languagehttps://www.mycodingcorner.com/2014/12/c-program-for-sorting-elements-using.html

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

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

Online Python Compiler

Leave a Reply

Your email address will not be published. Required fields are marked *