Bubble Sort in Python
Learn the Bubble Sort algorithm in Python! Step-by-step visual explanation with beginner-friendly, optimized Python code.
Try it yourself
Run this code directly in your browser. Click "Open in full editor" to experiment further.
Click Run to see output
Or press Ctrl + Enter
How it works
Bubble Sort is the most classic (and fun!) sorting algorithm to learn first. ๐
How It Works
Imagine you have a line of students, and you want them sorted by height. You walk down the line, and if you see a taller student standing in front of a shorter student, you politely ask them to swap places!
You keep repeating this until you can walk down the whole line without asking anyone to swap.
The largest items literally "bubble up" to the very end of the array during each pass. ๐ซง
1. Start at the beginning.
2. Compare two side-by-side elements.
3. Swap them if the left one is bigger.
4. Keep going!
Optimizations Let Us Chill
Our bubble_sort_optimized version tracks if we actually made any swaps. If we walk through the whole array and make zero swaps, it means we're perfectly sorted! We can instantly stop and grab a coffee. โ
Time Complexity
When to Use It?
Honestly? It's not great for huge datasets because O(n^2) is pretty slow. But it is an absolute must-know for learning how algorithms work, and it's incredibly easy to write and understand. Have fun watching those numbers bubble to the top!
Related examples
Fibonacci Sequence in Python
Learn how to code the famous Fibonacci Sequence in Python! A fun, beginner-friendly guide comparing recursion, loops (iteration), and clever memoization.
Binary Tree in Python
Learn Binary Trees in Python! A fun, beginner-friendly guide to building trees, inserting nodes, and exploring inorder, preorder, and postorder traversals.