How to implement, optimize and visualize Bubble Sort in Python

Code Specialist
7 min readFeb 20, 2021

In this post about the bubble sort algorithm in Python, we want to look into how to implement and visualize it. Bubble sort isn’t quite an efficient algorithm when it comes to time complexity. However, it is easy to code and understand, so it is often an introductory problem for computer science students and pupils.

The Concept Behind Bubble Sort

To remind yourself what the concept behind bubble sort is -not especially in Python- it might help look into its naming. Think of the analogy like that: you have some random air bubbles below the surface. The larger the bubble is, the higher its buoyancy speed is to rise to the top, and that’s it.

Bubbles below the surface — picture by MartinStr on pixabay.com

The algorithm's idea is to compare only two elements simultaneously and iterate over the whole list without going back. In the first step, you look at the first element in the list, in the second step at the second element, and in the last step, you look at the last element. You start at the beginning of the list and compare the first with the second item. If the first item is larger, you switch positions and go on.

Initial list: 	[4, 3, 2

--

--

Code Specialist
0 Followers

Creating content about Python, Algorithms and Code in general