Bubble sort in python

In this tutorial, we will implement bubble sort in python.

Bubble sort is a simple sorting algorithm. In bubble sort, we compare two adjacent elements and check if they are in correct order.If they are not in correct order, we swap them.
Here is a simple illustration of bubble sort.

Bubble sort

Above GIF is generated from algorithms app.

Here is simple code for bubble sort in python.

arr = [10,80,30,19,8,12,17]
print("Original array:",arr)
for i in range(len(arr)-1):
    for j in range(len(arr)-1-j):
        if arr[j] > arr[j+1]:
            temp = arr[j]
            arr[j] = arr[j+1]
            arr[j+1] = temp 

print("Sorted array:",arr)

Output:

Original array: [10, 80, 30, 19, 8, 12, 17]
Sorted array: [8, 10, 12, 17, 19, 30, 80]

Both worst case and average case complexity is O (n^2) for bubble sort.
That’s all about bubble sort in python.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.