Your sports day times are muddled. How can a computer put the fastest first?
Four runners finish a race at your school sports day. Their times come in jumbled, but the results board needs the fastest time first. Could you sort the whole list by comparing just two times at once?
In binary search, you used comparisons to decide which way to look. Here, twelve is less than eighteen, so twelve seconds goes first. Reverse the input order: eighteen is greater than twelve, so twelve seconds still goes first.
Look at eighteen and twelve, side by side in the list. Eighteen is bigger, so swap them. Now twelve comes first. If the left time is smaller or the same, leave the pair alone. Bubble sort applies this rule to adjacent times, meaning neighbours.
You’re sorting the times from smallest to largest. The neighbours you’re comparing are fourteen seconds on the left and nineteen seconds on the right. What should happen to this pair? Pick an answer.
Start with sixteen, eighteen, twelve and twenty seconds. Keep sixteen and eighteen in place. Move one position right: swap eighteen and twelve. Move right again: keep eighteen and twenty in place. That completes one pass. The list now reads sixteen, twelve, eighteen, twenty.
Start pass two back at the left. Swap sixteen and twelve. Keep sixteen and eighteen, then eighteen and twenty. There was a swap, so scan again. On pass three, keep twelve and sixteen, then sixteen and eighteen, then eighteen and twenty. This full pass made no swaps, so stop.
Try one pass starting with seventeen, thirteen, eleven and nineteen. Start at the left and compare each neighbouring pair in turn. After each comparison, move one position right. Pick the list you’ll have at the end of that one pass.
After pass one, you have sixteen, twelve, eighteen and twenty. Seeing twenty at the end might make you think the whole list is sorted. Check the first pair: sixteen is greater than twelve, so they’re out of order. The scan has already passed that pair, so it needs another pass.
Split the race times into halves, then split again into single items. Merge the single items in pairs, smaller first. To merge the sorted halves, compare their front values. Take twelve, then sixteen, then eighteen, each time taking the smaller front value. Only twenty remains, so add it at the end.