In [1]:
import ipytracer
from IPython.display import display

Bubble Sort

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

Complexity

Time

  • Worst-case: $O(n^2)$
  • Bast-case: $O(n)$
  • Average: $O(n^2)$

Reference

Code1 - List1DTracer


In [2]:
def bubble_sort(unsorted_list):
    x = ipytracer.List1DTracer(unsorted_list)
    display(x)
    length = len(x)-1
    for i in range(length):
        for j in range(length-i):
            if x[j] > x[j+1]:
                x[j], x[j+1] = x[j+1], x[j]
    return x.data

work


In [3]:
bubble_sort([6,4,7,9,3,5,1,8,2])


Out[3]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Code2 - ChartTracer


In [4]:
def bubble_sort(unsorted_list):
    x = ipytracer.ChartTracer(unsorted_list)
    display(x)
    length = len(x)-1
    for i in range(length):
        for j in range(length-i):
            if x[j] > x[j+1]:
                x[j], x[j+1] = x[j+1], x[j]
    return x.data

work


In [5]:
bubble_sort([6,4,7,9,3,5,1,8,2])


Out[5]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]