Musical Bubble Sort in Python

I am a firm believer in offering a wide variety of perspectives on the topics I teach in Computer Science. I also like to make connections between Computer Science and other subjects. To that end I give you:

Bubble sort presented via a non traditional medium, for your interest and consideration as a learning aid

You can hear it in action here:

 

This track was made using the Python programming language, along with a little library called musicalbeeps. You can find the package on Pypi here. To install it, simply use pip install musicalbeeps from a command line.

The code is basically just a plain old implementation of Bubble Sort in Python, with a few extra lines of code to handle playing the sound for each configuration of musical notes stored within a Python list.

I have provided the code below in case you want to try this out for yourself. As you are probably aware, Bubble Sort comes in several different flavours. I have provided two versions, both of which sort the data by “bubbling” the highest value towards the right-hand end of the list. The difference between the versions is that the first one continues to attempt to sort the data even when a full pass has been made with no swaps, while the second one uses this last condition as “proof” that the data is sorted, and so exits early.

Python Musical Bubble Sort in C Major Version 1

import musicalbeeps
import random

# notes = ["A", "Bb", "C5", "E5", "F5", "A5"]  # Phrygian Pentatonic anyone?
notes = ["C", "D", "E", "F", "G", "A", "B", "C5"]


def play_seq(seq):
    for pos in seq:
        player.play_note(notes[pos], 0.2)


def bubble_sort(arr):
    """
    Returns a list sorted in ascending order. We are assuming an integer list as input
    """
    length = len(arr)
    for passnum in range(length - 1):
        for i in range(length - 1 - passnum):
            if arr[i] > arr[i + 1]:
                temp = arr[i + 1]
                arr[i + 1] = arr[i]
                arr[i] = temp
            print("After Pass " + str(passnum + 1) + ", inner loop " + str(i + 1) + ":", arr)
            play_seq(arr)
            player.play_note("pause", 0.4)
        player.play_note("pause", 0.8)

    return arr


player = musicalbeeps.Player(volume=0.3,
                             mute_output=True)

initial = list(range(len(notes)))
initial = [0, 1, 3, 2, 4, 5, 6, 7]  # Comment as needed
# random.shuffle(initial)  # Uncomment as needed
print(bubble_sort(initial))

Python Musical Bubble Sort in C Major Version 2

This is the “early exit” version which is often more efficient.

import musicalbeeps
import random

# notes = ["A", "Bb", "C5", "E5", "F5", "A5"]
notes = ["C", "D", "E", "F", "G", "A", "B", "C5"]


def play_seq(seq):
    for pos in seq:
        player.play_note(notes[pos], 0.4)


def bubble_sort(arr):
    """
    Returns a list sorted in ascending order. We are assuming an integer list as input
    """
    length = len(arr)
    passnum = 0
    no_swaps = False
    while passnum < length - 1 and no_swaps is False:
        no_swaps = True
        for i in range(length - 1 - passnum):
            if arr[i] > arr[i + 1]:
                temp = arr[i + 1]
                arr[i + 1] = arr[i]
                arr[i] = temp
                no_swaps = False
            print("After Pass " + str(passnum + 1) + ", inner loop " + str(i + 1) + ":", arr)
            play_seq(arr)
            player.play_note("pause", 0.4)
        passnum += 1
        player.play_note("pause", 0.4)

    return arr


player = musicalbeeps.Player(volume=0.3,
                             mute_output=True)

initial = list(range(len(notes)))
initial = [0, 1, 3, 2, 4, 5, 6, 7]
# random.shuffle(initial)
print(bubble_sort(initial))

I encourage you to take this code as a starting point for your own experiments. Try changing some values, using other notes and scales etc. Maybe adapt the code for another algorithm like insertion sort.

A quick Word about Auditory Learning

Apparently “VAK” has been debunked. That is, no conclusive proof has been found that students have intrinsic differences in their ability to learn through visual vs auditory vs kinaesthetic modalities. However, this is a fundamentally different issue to whether learning through a variety of media is beneficial. It seems obvious to me, and the the research supports it, that presenting a subject through multiple channels will help with both the initial understanding and deepening/integrating learning. Beyond that, for learners with visual impairment or hearing problems, the difference in style is obviously very significant.

So beware then when you hear “VAK has been debunked” that you don’t wrongly assume that using visual and auditory and kinaesthetic means to teach and learn is “unscientific”. It may be that some activities are probably (or at least seem to be) more suited to a particular approach than others, but I would never want to be rigid about this and stifle pedagogical creativity.

OK, so that was just for people who have reservations about using fun, innovative, creative means of learning and teaching, while making fascinating cross-curricula connections that may well help students to stay engaged and motivated. For the rest of you, If music be the food of love, play on.

Happy Computing!

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *