Python Programming · High School (9–10) · 1 course, 13 worked problems, 20 practice questions
Finding a name in a list and putting marks in order are two of the most common jobs a program does. Linear search checks each item in turn, and it works on any list. Binary search needs a sorted list. It checks the middle item and throws away half of the list at each step, so it is much faster on long lists. Bubble sort swaps neighbouring items that are out of order, and insertion sort builds a sorted part one item at a time. Python also has sorted() and .sort(). Counting the steps lets you compare algorithms.
Choose an answer, then check it. Each one shows a full explanation.
A missing value: the target 9 is not in [4, 7, 1, 8]. How many comparisons does linear search make before it gives up?
Sorting by a key: what does print(sorted(['kiwi', 'fig', 'banana'], key=len)) show?
The first pass of bubble sort on [5, 2, 9, 1]: which value ends in the last place?
Each one has a hint, the key idea and a full worked solution.
A list grows from 1000 to 2000 sorted items. How many more checks, at most, does binary search need?
A linear search looks for 8 in [5, 3, 8]. How many items does it check?
What must be true about a list before you use binary search?
What does print(sorted([3, 1, 2], reverse=True)) show?
What is the largest number of steps that binary search needs for 100 items?
A student uses binary search on [9, 2, 7, 4], which is not in order, and sometimes it misses a value that is there. What is the mistake?
What does print(sorted(["b", "A", "c"])) show?