TExcelTAD
Home › Data Structures & Algorithms › A Simple Algorithm

A Simple Algorithm

Before the famous algorithms, let's design a small one from scratch and look at how we describe, implement and check it. Our problem: find the lowest value in a list of numbers, for example the cheapest price among several shops.

Step 1: Describe it in words

A good algorithm description is precise enough that someone else could follow it with pen and paper:

  1. Remember the first value as the "lowest so far".
  2. Look at each remaining value, one at a time.
  3. If the current value is lower than the lowest so far, remember it instead.
  4. When all values have been checked, the remembered value is the answer.

Step 2: Trace it by hand

Tracing means running the algorithm on a small input and writing down the state after each step. Let's let the program print the trace for us:

python · try it yourself
prices = [7.5, 6.2, 8.1, 5.9, 6.4]

lowest = prices[0]
print(f"start: lowest = {lowest}")
for i in range(1, len(prices)):
    p = prices[i]
    if p < lowest:
        lowest = p
        print(f"index {i}: {p} is lower -> lowest = {lowest}")
    else:
        print(f"index {i}: {p} is not lower, keep {lowest}")
print("answer:", lowest)
start: lowest = 7.5
index 1: 6.2 is lower -> lowest = 6.2
index 2: 8.1 is not lower, keep 6.2
index 3: 5.9 is lower -> lowest = 5.9
index 4: 6.4 is not lower, keep 5.9
answer: 5.9

Tracing small cases is the single best way to understand (and debug) any algorithm in this course.

Step 3: Turn it into a reusable function

python · try it yourself
def find_lowest(values):
    if not values:
        raise ValueError("cannot find the lowest value of an empty list")
    lowest = values[0]
    for v in values[1:]:
        if v < lowest:
            lowest = v
    return lowest

print(find_lowest([7.5, 6.2, 8.1, 5.9, 6.4]))
print(find_lowest([42]))
print(find_lowest([-3, -8, 0]))
try:
    find_lowest([])
except ValueError as err:
    print("error:", err)
5.9
42
-8
error: cannot find the lowest value of an empty list

Note: Think about edge cases: an empty list, a list with one item, negative numbers, duplicates. A correct algorithm handles all valid inputs and rejects invalid ones clearly.

Step 4: Count the work

For a list of n values the loop does exactly n - 1 comparisons, no matter what the values are. We say the algorithm runs in linear time, O(n): double the list, double the work. You cannot do better here, because every value might be the lowest, so every value must be looked at.

A second example: Fibonacci numbers

The Fibonacci sequence starts 0, 1, and every next number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, …. It appears in nature (sunflower spirals) and is a classic first algorithm because it can be written in several ways.

With a loop, we only need to remember the last two numbers:

python · try it yourself
def fibonacci_list(count):
    a, b = 0, 1
    result = []
    for _ in range(count):
        result.append(a)
        a, b = b, a + b
    return result

print(fibonacci_list(12))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

With recursion, the definition translates almost word for word: fib(n) = fib(n-1) + fib(n-2), with fib(0) = 0 and fib(1) = 1. A recursive function calls itself on smaller inputs until it reaches a base case.

python · try it yourself
calls = 0

def fib(n):
    global calls
    calls += 1
    if n <= 1:          # base cases: fib(0) = 0, fib(1) = 1
        return n
    return fib(n - 1) + fib(n - 2)

for n in [5, 10, 20]:
    calls = 0
    print(f"fib({n}) = {fib(n)} using {calls} calls")
fib(5) = 5 using 15 calls
fib(10) = 55 using 177 calls
fib(20) = 6765 using 21891 calls

The recursive version is elegant but wasteful: it recomputes the same values again and again, so the number of calls explodes. The loop version does only n steps. The Memoization lesson shows how to keep the recursive style and the speed.

Algorithm checklist

Question For "find the lowest"
What is the input? A non-empty list of numbers
What is the output? The smallest number
Does it always stop? Yes, after n - 1 comparisons
Is it correct? Yes: after checking index i, lowest is the minimum of the first i + 1 values
How fast is it? O(n) time, O(1) extra memory

The statement in the "Is it correct?" row is a loop invariant: something that is true before and after every iteration. When the loop ends, the invariant tells you the answer is right.

Test yourself

How many comparisons does "find the lowest" make on a list of 10 values?

  1. 5
  2. 9
  3. 10
  4. 100

What is a base case in a recursive function?

  1. The first line of the function
  2. An input that is answered directly, without a recursive call
  3. The largest input allowed
  4. A loop inside the function

Why is the simple recursive Fibonacci function slow for large n?

  1. Python cannot do recursion
  2. It recomputes the same smaller Fibonacci numbers many times
  3. It uses floating point
  4. Addition is slow