Python - Bubble Sort

 def bubble_sort(arr):

    """

    Sorts a list of elements in ascending order using the bubble sort algorithm.


    Args:

        arr: The list to be sorted.

    """

    n = len(arr)

    # Outer loop for number of passes

    for i in range(n):

        # Initialize swapped to False for early termination check

        swapped = False


        # Inner loop to compare adjacent elements

        # The last 'i' elements are already in place (sorted)

        for j in range(0, n - i - 1):

            # Compare current element with the next

            if arr[j] > arr[j+1]:

                # Swap elements if they are in the wrong order

                arr[j], arr[j+1] = arr[j+1], arr[j]

                swapped = True

        

        # If no two elements were swapped by inner loop,

        # then the list is sorted, and we can stop.

        if not swapped:

            break


# Example usage:

my_list = [64, 34, 25, 12, 22, 11, 90]


print(f"Original list: {my_list}")


bubble_sort(my_list)


print(f"Sorted list: {my_list}")




Comments