Implementing bubble sort

4 comments

Now you’re going to write a bubble sort program in Python. You’ll create a basic implementation to start with, and then try to make a few improvements.

You can start by creating a list that needs sorting.

my_list = [5,9,5,8,1,3]

Next you can create a function for the bubble sort algorithm. Give it a single parameter, which will be the data to be sorted.

def bubble_sort(unsorted):

Your function needs to do the following:

Here are a few hints to help you out.

sorted = old_list[:]

for i in range(len(sorted) - 1):

if sorted[i] > sorted[i+1]:

sorted[i], sorted[i+1] = sorted[i+1], sorted[i]

Have a go at generating the algorithm. If you get totally lost then you can have a peek at a solution on Rosetta Code.