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.
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:
Make a copy of the list, to leave the original untouched (this is not strictly necessary but will be important later on).
Initialise a swapped variable to be True.
Start a loop that runs until swapped is no longer True
Change swapped to False
Iterate over the unsorted list
Compare adjacent items in the list, and swap them if the first item is greater than the next
Change swapped back to True if 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 totally lost then you can have a peek at a solution on Rosetta Code.