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.
Pass 1: will 5 and 2 swap?
- 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.
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.
More to try
- IGCSE Computer Science · ToolLogic and truth tables How do you complete a truth table for a logic circuit?
- IGCSE Physics · SimulationBalance the beam What is the principle of moments?
- IGCSE Physics · SimulationPhases of the Moon Why does the Moon have phases?
- IGCSE Maths · SimulationProbability with two dice What is the most likely total when you throw two dice?
- IGCSE Maths · ToolGraphing calculator How do you find the roots and turning point of a quadratic graph?
- IGCSE Physics · ToolCircuits How do you work out resistance in series and in parallel?
113 lessons and 51 simulations in IGCSE Computer Science open at launch. The first 50 people to confirm their email get 50% off, and the next 50 get 25% off. Discounts are announced when ConceptOrbit opens.