Sorting - Bubble Sort

Bubble Sort is one of the simplest sorting algorithms used to arrange elements in a list in a specific order (ascending or descending). Despite its simplicity, it's an essential algorithm for understanding the basics of sorting techniques.

How Bubble Sort Works

Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Here's a step-by-step explanation:

  1. Start at the Beginning of the List: Compare the first two elements.

  2. Swap if Necessary: If the first element is greater than the second, swap them.

  3. Move to the Next Pair: Compare the second and third elements, and swap if necessary.

  4. Continue Through the List: Repeat the process for each pair of adjacent elements.

  5. Repeat the Entire Process: Go back to the beginning of the list and repeat the steps until no swaps are needed.

Each pass through the list places the next largest value in its proper place. This process is similar to bubbles rising to the surface—hence the name.

Time Complexity

  • Worst and Average Case: O(n²), where n is the number of elements in the list.

  • Best Case: O(n), when the list is already sorted.

def bubble_sort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n):
        # Initialize swapped as False
        swapped = False
        # Last i elements are already sorted
        for j in range(0, n - i - 1):
            # Traverse the array from 0 to n - i - 1
            # Swap if the element found is greater than the next element
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        # If no two elements were swapped by inner loop, then break
        if not swapped:
            break