2 min read

It is the simple sorting algorithm that works on the principle of repeated swapping of consecutive elements if they are placed at wrong place.

You have used the swapping concept in your daily life, same concept is applicable here only with the condition that you can swap only two adjacent element with each other.

Bubble Sort Gif

Now Its time for implementation of bubble sort in Python.

Python Code for Bubble Sort

# Bubble Sort Published on Freshlybuilt.com

def bubble_sort(input_list):
    # Swap the elements to arrange in order
    for iter_num in range(len(input_list) - 1, 0, -1):
        for idx in range(iter_num):
            if input_list[idx] > input_list[idx + 1]:
                temp = input_list[idx]
                input_list[idx] = input_list[idx + 1]
                input_list[idx + 1] = temp
        print(f"Iteration decreasing number {iter_num}:", input_list)
    return input_list

def main():
    lst = [8, 17, 3, 9]
    print("Initial Unsorted List:", lst)
    bubble_sort(lst)
    print("After Sorting:", lst)


if __name__ == "__main__":
    main()

Output

Initial Unsorted List: [8, 17, 3, 9]
After Sorting: [3, 8, 9, 17]

Flowchart for Bubble sort in Python

Flowchart for optimized Bubble sort in Python

Now, Its time for short video of less than 2 min with live implementation of given code.

Some Facts about bubble sort algorithm

Best Case ComplexityO(n)
Average Case ComplexityO(n^2)
Worst Case ComplexityO(n^2)
Auxiliary SpaceO(1)
Sorting in PlaceYes
StableYes
Best Case OccurrenceThe best case occurs when an array is already sorted.
Worst Case OccurrenceThe worst-case only occurs when an array is sorted in the reverse order.

Now finally our blog post come to an end. If you liked it, Please share our blog post with other friends also. Happy Coding 🙂

1+

Vishal Sharma

Currently pursuing Computer Science degree from G.B Pant Government Engineering college, New Delhi.

0 Comments

Leave a Reply