Implementing bubble sort

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.

Share this article:

This article is from the free online course:

Programming 102: Think Like a Computer Scientist

Raspberry Pi Foundation