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.
Your function needs to do the following:
- Make a copy of the list, to leave the original untouched (this is not strictly neccessary but will be important later on)
- Initialise a
swappedvariable to be
- Start a loop that runs until
swappedis no longer
- Iterate over the
- Compare adjacent items in the list, and swap them if the first item is greater than the next
Trueif a swap has been made
- 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.