Skip main navigation

Implementing bubble sort

Read James Robinson's advice for implementing bubble sort in Python, and give it a go yourself.

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.

Let’s begin 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:
1. Make a copy of the list, to leave the original untouched (this is not strictly neccessary but will be important later on)
1. Initialise a swapped variable to be True
2. Start a loop that runs until swapped is no longer True
3. Change swapped to False
4. Iterate over the unsorted list
5. Compare adjacent items in the list, and swap them if the first item is greater than the next
6. Change swapped back to True if a swap has been made
7. Return the ordered list, if no swaps have been made after a full iteration

Here are a few hints to help you out.

  • Making a copy of a list:
sorted = old_list[:]
  • Iterating over the list. You don’t need to look at the last item in the list, as there is nothing following it that it could be swapped with.
for i in range(len(sorted) - 1):
  • Comparing items:
if sorted[i] > sorted[i+1]:
  • Swapping list items around:
sorted[i], sorted[i+1] = sorted[i+1], sorted[i]

Have a go at generating the algorithm. If you get stuck, why not ask for a few hints in the comments? If you get totally lost then you can have a peek at a solution on Rosetta Code.

Use the comments section to discuss the challenge and get help if needed. You’ll share your code in a later step.

This article is from the free online

Programming 102: Think Like a Computer Scientist

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education