Data Structures & Algorithms
Lesson 2 of 4 9 min +75 XP

Sorting Algorithms

Putting data in order, and what it costs.

What you'll learn

  • Describe how bubble sort works
  • State bubble sort's time complexity
  • Contrast it with faster sorts
Sorting a hand of cards

Dealt a messy hand, you slide each card into its place until the whole hand is in order. Computers sort data with strategies like this, and each strategy has a cost — some breeze through a shuffled deck, others crawl.

Bubble sort, step by step

Bubble sort repeatedly walks the list, comparing each neighboring pair and swapping them if they're out of order. After each full pass the largest remaining value 'bubbles' to the end. It's simple but slow: O(n²) comparisons.

Simulation · Bubble sort visualizer

comparing positions 0 and 1

Press Step to perform one comparison/swap. Watch the largest bar bubble to the right each pass.

Lab · Count the work
  1. Shuffle the bars and step until sorted.
  2. Notice you compare nearly every pair on every pass.
  3. Imagine doing this for 1,000 items.

What you should see: The number of comparisons grows with n², which is why O(n log n) sorts like mergesort are preferred at scale.

Knowledge Check

+20 XP / correct

1. What is the worst-case time complexity of bubble sort?

2. After one full pass of bubble sort, what is guaranteed?