Back

An algorithm and Python code for bubble sorting

The algorithm for a bubble sort is perhaps a little easier to understand than the insertion sort algorithm. A first attempt might be something like this:

We get a list.
We then need to get the length of the list and subtract 1 from it, to give the number of passes we need to do.
For each pass:
    we need to check pairs of elements in turn until there are no more pairs, starting with the first pair.
    If we need to swap them
        swap them!

If we wrote this in Python, we would probably produce code similar to this:

def bubble(myList):
    for passnumber in range(len(myList)-1,0,-1):
        for i in range(passnumber):
            if myList[i]>myList[i+1]:
                temp = myList[i]
               myList[i] = myList[i+1]
               myList[i+1] = temp

anyList = [54,26,93,17,77,31,44,55,20]
bubble(anyList)
print(anyList)

Here, we have defined a bubble function called bubble. To call it, we just state the name and what list we want to use. We then print it out.

Q1. Type the above code in and get it working.
Q2. Change the data in the list and check it still works.
Q3. Using the code you used when you studied insertion sorting, generate a random set of data and use that rather than the fixed set of data used in the above example.
Q4. Print out the list after each comparison between two data items, by using the code you used when you studied insertion sorting.

Extension task
a) Modify your program so that you generate some random data, then sort that data using both insertion sort and the same data using bubble sort. You should print out the results after each pass, so you can see how each method of sorting worked.

To do this, you must create a list of data. You must then copy it twice, and use one copy for the bubble sort and the other copy for the insertion sort. You can easily make duplicates of lists in Python. If your original list of data is called anyList, then to make two new lists, do this:

anyList1 = anyList[:]
anyList2 = anyList[:]

Now you would use anyList1 for the bubble sort and anyList2 for the insertion sort.

b) Repeat the above experiment using a fixed list of animals rather than numbered data. Remember to duplicate the list of animals.

Back