Join the waiting list

IGCSE Computer Science · Simulation · 7.4

Bubble sort, step by step

How does bubble sort work?

Bubble sort works through a list comparing each pair of neighbouring items and swapping them if they are in the wrong order. Each pass moves the largest unsorted value to its final place at the end. The sort stops after a pass with no swaps, so a list that is already sorted needs only one pass.

Bubble sort, step by stepComputer Science · Algorithms

Pass 1: will 5 and 2 swap?

comparing528163123456
Pass
1
Comparisons · swaps
0 · 0
Predictions right
0 of 0
REPEAT    Swapped ← FALSE    FOR Index ← 1 TO Last − 1        IF List[Index] > List[Index + 1]            THEN                Temp ← List[Index]                List[Index] ← List[Index + 1]                List[Index + 1] ← Temp                Swapped ← TRUE        ENDIF    NEXT Index    Last ← Last − 1UNTIL NOT Swapped

Tasks0 of 3 done

  • Finish the first pass, so the biggest number reaches the end.
  • Predict five comparisons correctly.
  • Sort the whole list.

Free to use here, with no account.

What to take away

  • Bubble sort compares neighbouring items and swaps them if they are in the wrong order.
  • Each pass puts the largest unsorted value into its final place at the end.
  • It stops after a pass with no swaps, so an already sorted list needs only one pass.

Common mistakes

  • Thinking one pass sorts the list, rather than putting one more value in its final place.
  • Not seeing why it stops: a pass with no swaps means the list is in order.

Put Bubble sort, step by step on your own site

Free for teachers, schools and anyone writing about IGCSE Computer Science. Paste this code where you want it: the simulation runs in your page, with a line under it saying where it’s from.

<iframe src="https://www.conceptorbit.com/embed/bubble" title="Bubble sort, step by step: a ConceptOrbit simulation" width="100%" height="1180" style="border:0;max-width:960px" loading="lazy"></iframe>
<p><a href="https://www.conceptorbit.com/computer-science/playground/bubble">Bubble sort, step by step</a>, a free IGCSE Computer Science simulation from <a href="https://www.conceptorbit.com">ConceptOrbit</a>.</p>

Questions

How does bubble sort work?

Bubble sort works through a list comparing each pair of neighbouring items and swapping them if they are in the wrong order. Each pass moves the largest unsorted value to its final place at the end. The sort stops after a pass with no swaps, so a list that is already sorted needs only one pass.

When does bubble sort stop?

After a pass in which nothing is swapped, because then every neighbouring pair is in order. A flag set to false at the start of each pass and to true on any swap tells the algorithm when that has happened.

Is bubble sort efficient?

Not on long lists. It is simple to write and easy to trace, but the number of comparisons grows with the square of the number of items.