What makes an algorithm?
An algorithm is a finite, clearly defined sequence of steps for solving a problem. A good algorithm has clear inputs, outputs and termination.
Linear search
Linear search checks one item at a time. It works on unsorted data. In the worst case it checks all n items: O(n).
def linear_search(values, target):
for i in range(len(values)):
if values[i] == target:
return i
return -1Binary search
Binary search repeatedly halves the search interval, but requires a sorted list. Its worst-case time is O(log n).
Bubble sort
Adjacent values are compared and swapped if out of order. Repeated passes gradually move larger values to the end; worst-case O(n²).
Practise
Trace linear search for 7 in [3, 9, 2, 7, 5]. How many comparisons occur? Explain why binary search cannot reliably be used on this unsorted list.
Suggested answer
Four comparisons; binary search relies on ordered values so each half can be safely discarded.
