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

1352 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What is Object-Oriented Programming?


Demonstrate a recursive solution to calculate the factorial of a number


How would you get a piece of code to print the numbers 1 to 10


How do I check if a number is prime using a python program?


We're here to help

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

© MyTutorWeb Ltd 2013–2024

Terms & Conditions|Privacy Policy