Bubble Sort Python Program using List

Bubble sort is one such data structure program that every computer science student must learn. This sorting program arranges the liven list element in ascending /descending order.

How Bubble Sort Works ( Ascending Order )

first of all first element compare itself with the next element, if the second element is less than the first element then both element exchange their position.

Now second position element compares itself with the next position element if the third position element is less than the second position element then they exchange their position otherwise they do not exchange their position.

This process continues until the largest number settle down at the bottom. Once it settles down at bottom it is said that the first phase of sorting is complete.

Now the second phase of sorting start, it again starts from the top position and repeats the process until second-largest number take place its position at the second place from the bottom.

This way n-1 phases takes place to sort the whole list. a simple first phase demonstration is shown in this picture.

Bubble sort method working

Bubble Sort Program using List

x = [3, 56, 2, 56, 78, 56, 34, 23, 4, 78, 8, 123, 45]
n = len(x)
for i in range(n):
    for j in range(0, n-i-1):
        if(x[j] > x[j+1]):
            x[j], x[j+1] = x[j+1], x[j]

print("Sorted Array :")

The output of Bubble sort program

rakesh@folio MINGW64 /e/python (master)
$ C:/Python37/python.exe e:/python/DataStructure/bubble_sort.py
Sorted Array :
2 3 4 8 23 34 45 56 56 56 78 78 123

Extra Challenge for you: Since list can store different type of data in a list, You are requested to sort any list, If all the elements of the list are of the same type.

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.