Python – Bubble Sort Example

Hello everyone, in this tutorial, we will learn how to write a simple Bubble Sort in python programming language. This example program has been tested and shared in the same post.

What is Bubble Sort?

The bubble sort is one of the easiest sorting algorithm that works by iteratively swapping an elements if they are in the wrong order. The below example will give you an idea about swapping based on the iteration.

[4, 2, 1, 5, 3]
[4, 2, 1, 5, 3]
[4, 2, 1, 5, 3]     -> Iteration 1
[5, 2, 1, 4, 3]
[5, 2, 1, 4, 3]


[2, 5, 1, 4, 3]
[2, 5, 1, 4, 3]
[2, 5, 1, 4, 3]     -> Iteration 2
[2, 5, 1, 4, 3]
[2, 5, 1, 4, 3]


[1, 5, 2, 4, 3]
[1, 2, 5, 4, 3]
[1, 2, 5, 4, 3]     -> Iteration 3
[1, 2, 5, 4, 3]
[1, 2, 5, 4, 3]


[1, 2, 5, 4, 3]
[1, 2, 5, 4, 3]
[1, 2, 4, 5, 3]     -> Iteration 4
[1, 2, 4, 5, 3]
[1, 2, 4, 5, 3]


[1, 2, 4, 5, 3]
[1, 2, 4, 5, 3]
[1, 2, 3, 5, 4]     -> Iteration 5
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

Function – Bubble Sort in Python

The below function is responsible to sort a given numbers array by using Bubble Sort algorithm.

def bubbleSort(numbers):
    for i in range(numbers.__len__()):
        for j in range(numbers.__len__()):
            if numbers[i] < numbers[j]:
                temp = numbers[i]
                numbers[i] = numbers[j]
                numbers[j] = temp

Creating a numbers array and passing the same to the function, In order to perform the bubble sort.

numbers = [4, 2, 1, 5, 3]

bubbleSort(numbers)

print(numbers)

Output

[1, 2, 3, 4, 5]

References