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).

TD
Answered by Tutor156882 D. Python tutor

1920 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What does __init__ mean?


Write a recursive function to return the nth Fibonacci number in Python


Write a basic program to output the lowest of 3 input numbers. (You may omit error checks on your inputs)


Firstly, my question is not Python related, but maths A-level related. I don't know how to change that in my profile but I would like to only tutor maths GCSE and potentially A-level. My question: Integrate sin(x)^3 over x=0 and x=pi/2.


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences