KTU S1

Developing an Algorithm

By the end you should be able to: Write an algorithm as a finite, unambiguous, terminating sequence of steps, and evaluate two algorithms for the same problem by counting steps.

An algorithm is a finite sequence of unambiguous instructions that, given valid input, terminates and produces the correct output.

Every word in that definition is load-bearing.

The five required properties

PropertyMeaningViolated when…
FinitenessMust stop after a finite number of stepsAn infinite loop
DefinitenessEach step precisely defined"Choose a suitable value"
InputZero or more well-specified inputsInput type left unstated
OutputAt least one outputNothing is produced
EffectivenessEach step basic enough to be carried out"Solve the problem" as a step

An examiner asking "why is this not an algorithm?" is asking which of these five fails.

Language: neither English nor Python

An algorithm sits between the two. Plain English is ambiguous; Python commits you to syntax before the logic is settled. Write algorithms in structured steps — numbered, one action each, using words like if, repeat, while, set.

You'll formalise this as pseudocode in Module 2.

Example: largest of n numbers

1. Read n
2. Read the first number, call it max
3. Repeat (n - 1) times:
       a. Read the next number, call it x
       b. If x > max, set max = x
4. Output max

Check the properties: it stops after n reads (finite); each step is exact (definite); it takes n numbers (input); it prints one (output); every step is a read or a comparison (effective). ✓

Comparing algorithms by counting steps

This is a KTU classroom exercise for this module: "Evaluate different algorithms based on their efficiency by counting the number of steps."

To find whether a value exists in a sorted list of 1,000 items:

Linear search — check each in turn. Worst case: 1,000 comparisons.

Binary search — check the middle, discard half, repeat. Worst case: log⁡21000≈10\log_2 1000 \approx 10 comparisons.

Both are correct. One does a hundred times less work. Counting steps is how you tell them apart, and it's why the same problem can have better and worse solutions.

Note that binary search requires a sorted list. Correctness first, efficiency second — a fast wrong answer is worth nothing.

Desk checking

Before coding, trace your algorithm on paper with a small input, writing down each variable's value at each step.

For the largest-of-n algorithm with input 4, [3, 9, 2, 7]:

Stepxmax
Read first–3
Iteration 199
Iteration 229
Iteration 379
Output–9

Ten minutes of desk checking catches logic errors that would take an hour to find once buried in code.