Bubble Sort: The Implementation

This is part of a series on Bubble Sort that began with a look at the Bubble Sort Algorithm and continues now with a python translation of the algorithm.

Some Setup

Imports

# python
from random import choices

# pypi
from expects import contain_exactly, equal, expect

Bubble Sort

The Implementation

Here's a straight-forward translation of the pseudocode to python.

def bubble_sort(unsorted: list) -> list:
    """Sorts the unsorted

    Args:
     unsorted: mutable collect of orderable items

    Returns:
     original list sorted in ascending order
    """
    all_but_one = len(unsorted) - 1
    for items_bubbled_up in range(all_but_one):
        for left_hand in range(all_but_one - items_bubbled_up):
            right_hand = left_hand + 1
            if unsorted[right_hand] < unsorted[left_hand]:
                (unsorted[left_hand],
                 unsorted[right_hand]) = (unsorted[right_hand],
                                          unsorted[left_hand])
    return unsorted

Try It Out

inputs = [6, 3, 4, 5, 0]
expect(bubble_sort(inputs)).to(contain_exactly(0, 3, 4, 5, 6))

population = list(range(1000))
scrambled = choices(expected, k=1000)
expect(bubble_sort(scrambled)).to(contain_exactly(*list(sorted(scrambled))))

Well, that wasn't so exciting, but that's because I'm going to look more at how the sort performs in the next post.

Up Next

In the next post I'll run the function over some inputs to see how it performs.