# How the Bubble Sorting technique is implemented in Python

In this Python tutorial, we are about to implement bubble sort in Python programming language. Bubble Sort is one of the basic, simple algorithm and easy to implement to sort items. Before implementing in Python, we will learn the how bubble sorting works. So let’s start learning bubble sort in Python.

## How bubble sort works in Python

The input to this algorithm is an unsorted list.This unsorted list compares each element with the right side of it’s neighbour in order to sort the data. The element which is smaller will shift towards the left side. After one iteration one of the element will be in it’s the correct position. This iteration continues until all the elements are in their correct position.

Performance :- The worst case and average case of order of complexity of bubble sort is O(*n*^{2}). Here n is the number of items need to be sorted.

## Implementation of Bubble Sort in Python

Here is the Python code to implement bubble sort algorithm

**Python Code of bubble sort**

def bubble(list): for i in range(len(list) - 1, 0, -1): no_swap = True for k in range(0, i): if list[k + 1] < list[k]: list[k], list[k + 1] = list[k + 1], list[k] no_swap = False if no_swap: return list = input('Enter the list of numbers: ').split() list = [int(x) for x in list] bubble(list) print('Sorted list: ', end='') print(list)

Note: Use spaces after each number you insert and hit enter after entering all the numbers to be sorted.

**Explanation of bubble sorting in Python**

First, create an unsorted list. Create a function that takes this unsorted list as an argument. Create a method inside the loop with loop variable * i *that counts the length of the list. Create an inner loop inside the loop with loop variable j which counts the elements from zero to i. If the inner loop contains elements which are not in order that means list[j] and list[j+1] are out of order. If in any one of the iteration there are no swaps then the list is sorted and returns the sorted list.

**Output of the program:-**

Enter the list of numbers: 5 4 3 2 1 7 8 9 0 Sorted list: [0, 1, 2, 3, 4, 5, 7, 8, 9]

You can also read,

Implementation of Queue in Python

Implementation of Stack in python

## Leave a Reply