Python: Implement Bubble Sort Algorithm – A Step Guide

In this tutorial, we will introduce how to implement bubble sort algorithm in python.

Python - Implement Bubble Sort Algorithm - A Step Guide

1.Create a unsorted list

unsorted_list = [8,5,3,6,2,1,9,4,7]

2.Implement binary search algorithm using a function

def bubble_sort(unsorted_list):
    
    sequence = unsorted_list[:]
    
    # For each value of the sequence (epochs),
    for i, _ in enumerate(sequence):
        # For each value of the sequence,
        for i, _ in enumerate(sequence):
            # Try
            try:
                # If a value is greater than the value that follows it
                if sequence[i] > sequence[i+1]:
                    # Swap the values in the sequence
                    sequence[i], sequence[i+1] = sequence[i+1], sequence[i]
            # If you raise an index error, you are at the end of the sequence,
            except IndexError:
                # So ignore the error and continue with iteration
                continue
                
        # Print the sequence afer each epoch
        print(sequence)

3.Sort data

bubble_sort(unsorted_list)

Run this code, you will see this sorted list:

[5, 3, 6, 2, 1, 8, 4, 7, 9]
[3, 5, 2, 1, 6, 4, 7, 8, 9]
[3, 2, 1, 5, 4, 6, 7, 8, 9]
[2, 1, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]