Computers search and sort lists all the time, from finding a contact in your phone to ranking the scores in a game. Try the same algorithms a computer uses: search a row of cards, find a number in just a few guesses, sort numbers with bubble sort, then race three sorting algorithms to see which is fastest. Ages 10-14.
In a linear search you check the items one at a time, from start to end, until you find what you want. These cards are in no particular order. Tap cards to turn them over and find the target. Watch out: sometimes the number isn't there at all!
These cards are sorted from smallest to largest. In a binary search you check the middle card. If the target is bigger, rule out the left half. If it is smaller, rule out the right half. Every guess cuts the cards in half!
| Items in the list | Linear search | Binary search |
|---|---|---|
| 10 | 10 | 4 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
Binary search is much faster, but it only works if the list is sorted first. That's one big reason computers sort things!
Bubble sort compares two neighbours at a time. If the left one is bigger, swap them. Then move one step to the right. After each pass through the list, the biggest unsorted number has bubbled to the end and is locked in place (green). Sort the numbers from smallest to largest.
Three algorithms sort the same numbers. Every tick, each one makes one comparison, so the algorithm that needs the fewest comparisons wins. Insertion sort takes each number in turn and slides it back into the right place. Merge sort splits the list into tiny pieces, then merges them back together in order. Try different start orders and see who wins!
10 questions. ·
Want to know more? Write your own step-by-step instructions with Algorithms: Program the Robot, then learn about variables, if and loops with Coding Basics.