BUBBLE SORT IN PYTHON

Bubble Sort in Python

Bubble sort is one of the import sorting technique which is implemented in many languages. Here we can implement Bubble Sort technique in Python as well. For this we need an array (Same Data element) which is nothing but a List in Python. The technique is to sort the adjacent element in order (ascending or descending). It you will do so, the largest element in the array will get sorted in every pass. So after every pass one largest element will get sorted in ascending order if sorting is done in ascending order. Here is the sample code for bubble sort and its output after every pass.

'''
Created on Jan 10, 2020<br>
Bubble sort implemented in Python in ascending<br>
order using List.<br>
@author: admin@pythonport.com<br>
'''
lst = [56, 778, 87, 55, 11, 33, 97]
print('Original list is - ', lst)
n = len(lst)
for i in range(n):
     for j in range(0, n - i - 1):
         if lst[j] > lst[j + 1] :
             lst[j], lst[j + 1] = lst[j + 1], lst[j]    
     print('Sorted list after {0} - {1}'.format(i+1,lst))
 print('Sorted list is - ', lst)

Output of above code will look like –

Original list is – [56, 778, 87, 55, 11, 33, 97]
Sorted list after 1 – [56, 87, 55, 11, 33, 97, 778]
Sorted list after 2 – [56, 55, 11, 33, 87, 97, 778]
Sorted list after 3 – [55, 11, 33, 56, 87, 97, 778]
Sorted list after 4 – [11, 33, 55, 56, 87, 97, 778]
Sorted list after 5 – [11, 33, 55, 56, 87, 97, 778]
Sorted list after 6 – [11, 33, 55, 56, 87, 97, 778]
Sorted list after 7 – [11, 33, 55, 56, 87, 97, 778]
Sorted list is – [11, 33, 55, 56, 87, 97, 778]

Thank you . Please post comment you have any query based on Bubble sorting.