How might we implement the bubble sort algorithm in Python

Largely shown in code with a talk-through of what I'm doing. First discuss what the algorithm is doing, then talk through Python implementation with pythonic practices in mind e.g. why use a function, and discuss how to test it for correctness. The bubble sort algorithm is a finite sorting algorithm meaning given a valid input list of integers, it can output them in ascending or descending order, depending on the implementation.
We want to write it in Python, but first it might be a good idea to figure out what exactly the algorithm is doing in order to achieve this output. The clue for this is in the name, and roughly speaking it does indeed sort a list by bubbling elements through it. More precisely, it steps through the list making pairwise comparisons i.e. comparing two consecutive elements of the list to see how they should be ordered. If they are in the wrong order, then swap them and move focus one forward in the list. Continue this process until the end of the list is reached.
If we take the list 5, 1, 2, 3, 4 for example. We initially look at 5 and 1, noting that 5 is greater than 1. In this instance suppose we want a list in ascending order. Then we would swap 5 and 1 to get 1, 5, 2, 3, 4. Next we look at 5 and 2, again these must be swapped and so on. By the fourth step we have a correctly sorted list in this pretty trivial example. Now, there are a few things to consider when it comes to implementing this algorithm. How many times must we repeat this until the list is fully sorted? How can we swap the elements? (Will show this in code).

Answered by Tutor156882 D. Python tutor

1746 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

How can you take a list of numbers and add 3 to every number in the list using only one line of code?


Generate an array of integers from 0 to 99 and split it into two smaller arrays. Each smaller array will contain half of the original.


What is the outcome of the following code? print(2*[3,4,5])


What are docstrings and how do I use them to improve my code readability?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences