Bubble Sort

Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n^2) algorithm.

Key Idea

Each iteration the largest element will be bubbled to the top.

Debug

Why this implementation is wrong? hint: what do you know for sure after each iteration in the outer loop?

def sortIntegers(self, A: List[int]) -> None:
    """
    Bubbling up the current element to the end of the list is also an option.
    """
    
    n = len(A)
    for i in range(n):
        for j in range(i, n-1):
            if A[j] > A[j+1]:
                temp = A[j]
                A[j] = A[j+1]
                A[j+1] = temp

Code

Time & Space Complexity

Bubble sort has quite a few nice properties. Since it only involves swapping elements, it is in-place. The finishing order is also stable. The time complexity can be calculated with a simple summation i=0n1i=n2\sum\limits_{i=0}^{n-1} i = n^2.

Optimization

We can add a flag to check if the inner loop has 0 swaps. That will improve the best case to O(n).

Last updated