AlgorithmsBeginner

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.

Loading...

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

  • Best case time: O(n) โ€” If the array is already sorted, we just check it once and we're done! (thanks to our optimization)
  • Average/Worst time: O(n^2) โ€” If it's reversed, we have to do a lot of swapping.
  • Space Complexity: O(1) โ€” We do all the sorting right inside the original array! So no extra memory needed.
  • 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

    Keywords: python bubble sort, bubble sort python, bubble sort algorithm python, sorting algorithm python, python sort list, bubble sort code, bubble sort example, bubble sort explained