Bubble Sort Algorithm in Python

In this source code example, we will write a code to implement the Bubble Sort algorithm in Python.

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

Bubble Sort Algorithm in Python

In this Python program, we will take input from the User or console and print the result to the output:
def bubble_sort(collection):

    length = len(collection)
    for i in range(length - 1):
        swapped = False
        for j in range(length - 1 - i):
            if collection[j] > collection[j + 1]:
                swapped = True
                collection[j], collection[j + 1] = collection[j + 1], collection[j]
        if not swapped:
            break  # Stop iteration if the collection is sorted.
    return collection


if __name__ == "__main__":
    import doctest
    import time

    doctest.testmod()

    user_input = input("Enter numbers separated by a comma:").strip()
    unsorted = [int(item) for item in user_input.split(",")]
    start = time.process_time()
    print(*bubble_sort(unsorted), sep=",")
    print(f"Processing time: {time.process_time() - start}")

Output:

Enter numbers separated by a comma: 10, 5, 2, 4, 20
2,4,5,10,20
Processing time: 6.436199999999836e-05

Related Algorithms in Python

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course