Course contentsShow
← Computer Science
Lesson 741 of 2,87218. Sorting AlgorithmsFree lesson

Bubble Sort: Algorithm

Learning bubble sort: repeatedly swap adjacent out-of-order elements until the array is sorted.

Bubble Sort: Algorithm

What you'll learn: You'll discover how bubble sort works by repeatedly comparing and swapping adjacent elements until your array becomes sorted.

The Core Idea

Bubble sort is one of the simplest sorting algorithms. Imagine bubbles in water rising to the surface—larger values "bubble up" to their correct positions at the end of the array. The algorithm makes multiple passes through your data, and on each pass, it compares pairs of adjacent elements. If two neighbors are out of order (the left one is bigger than the right one), it swaps them. This process repeats until no more swaps are needed, meaning everything is sorted.

How It Works Step-by-Step

  1. Start at the beginning of your array
  2. Compare the first two elements—if the first is greater than the second, swap them
  3. Move one position forward and compare the next pair
  4. Continue to the end of the array—the largest element is now in its final position
  5. Repeat the entire process for the remaining unsorted portion
  6. Stop when you make a complete pass with zero swaps

Think of it like organizing a line of students by height: you walk down the line, and whenever you find someone taller standing before someone shorter, you have them switch places. You keep making passes until everyone stands in the right order.

Why "Bubble"?

The name comes from how smaller elements gradually "bubble" toward the beginning of the array, while larger elements sink toward the end—like air bubbles rising in water.

Key Takeaway: Bubble sort repeatedly swaps adjacent out-of-order elements across multiple passes through the array until no swaps remain, achieving a fully sorted result through simple comparison-based exchanges.