Write a Program in Python to execute Bubble sort program

What is Bubble Sort Program ?

Bubble sort is a simple sorting algorithm that compares adjacent elements and swaps them if they are in the wrong order. It will compares through the list until the list is completely sorted.

Let’s take this array “6, 1, 3, 4, 2”, and sort it from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required;
First Pass
6 1 3 4 2 ) → ( 1 6 3 4 2 ), Here, algorithm compares the first two elements, and swaps since 6 > 1.
( 1 6 3 4 2 ) → ( 1 3 6 4 2 ), Swap since 6 > 3
( 1 3 6 4 2 ) → ( 1 3 4 6 2 ), Swap since 6 > 4
( 1 3 4 6 2 ) → ( 1 3 4 2 6 ), swap since 6 > 2

Second Pass

1 3 4 2 6 ) → ( 1 3 4 2 6 ), No change as 1 < 3
( 1 3 4 2 6 ) → ( 1 3 4 2 6 ), No change as 3 < 4
( 1 3 4 2 6 ) → ( 1 3 2 4 6 ), swap since 4 > 2
( 1 3 2 4 6 ) → ( 1 3 2 4 6 ), No change as 4 < 6

Third Pass
1 3 2 4 6 ) → ( 1 3 2 4 6 ) ,
( 1 3 2 4 6 ) → ( 1 2 3 4 6 ), Swap since 3 > 2
( 1 2 3 4 6 ) → ( 1 2 3 4 6 )
(  1 2 3 4 6 ) → ( 1 2 3 4 6 )

#bubblesort.py
def bubblesort(n):
    l = len(n)
    for i in range(l-1):
        for j in range(0, l - i - 1):
            if n[j] > n[j+1]:
                n[j], n[j+1] = n[j+1], n[j]

arr = [6,1,3,4,2]
print("Input array :")
print(arr)
bubblesort(arr)
print("Sorted array :")
print(arr)

Output

$python bubblesort.py 
Input array :
[6, 1, 3, 4, 2]
Sorted array :
[1, 2, 3, 4, 6]
(Visited 317 times, 4 visits today)