An algorithm is the heart of every program. Before comparing algorithms we must know what one is, how it is designed, and what we mean by its performance.
What Is an Algorithm
An algorithm is a finite sequence of well-defined steps that takes some input and produces the required output. Every algorithm must have five properties: input (zero or more values supplied), output (at least one result), definiteness (each step is clear and unambiguous), finiteness (it stops after a finite number of steps for every input) and effectiveness (each step is basic enough to be carried out exactly). A recipe that says "add salt to taste" is not definite; a loop that never terminates is not finite. The word comes from the name of the ninth-century Persian mathematician al-Khwarizmi.
Definition: Algorithm. A finite, unambiguous sequence of effective steps that transforms a given input into the desired output and always terminates.
Designing an Algorithm
Design starts with understanding the problem exactly: what is given, what is required, what are the constraints. Then one chooses a design technique. The main ones, each a separate topic of this course, are brute force (try everything), divide and conquer (split, solve, combine), greedy (take the best local choice), dynamic programming (store sub-answers and reuse them) and backtracking (build a solution step by step and undo wrong steps). After design comes proof of correctness, then analysis, then coding. An algorithm may be written in plain language, as a flowchart, or as pseudocode, which is the usual form in textbooks because it is language independent.
Why Analyse Performance
A computer is fast, but not infinitely fast; memory is large, but not infinite. If an algorithm takes time proportional to n for n items, a thousand times more data takes a thousand times more time; if it takes time proportional to n², it takes a million times more. Performance analysis predicts how much time and space an algorithm needs, so we can pick the better one before writing code and without depending on a particular machine. Two approaches exist. Posteriori analysis runs the program and measures seconds, but the result depends on the computer, the language and the compiler. Apriori analysis counts the number of basic steps as a function of the input size n, which is machine independent, and this is the approach we use.
Time Complexity
Time complexity T(n) is the number of basic operations the algorithm performs on an input of size n. We choose a basic operation, usually the one executed most often, such as a comparison inside the innermost loop, and count it. The count may differ for inputs of the same size, so we distinguish three cases. The best case is the input on which the algorithm does the least work; the worst case is the input on which it does the most; the average case is the expected work over all inputs. The worst case is most often quoted because it is a guarantee: the algorithm will never be slower.
Space Complexity
Space complexity S(n) is the memory the algorithm needs: a fixed part (code, simple variables, constants) and a variable part that grows with n (arrays, recursion stack). When counting, we usually ignore the space taken by the input itself and report only the extra space; an algorithm that works in the same array is called in place. For example, selection sort needs a handful of extra variables, O(1), but merge sort needs a second array of size n.
Table 1.1: Time and space at a glance
| Measure | What is counted | Example |
|---|---|---|
| Time complexity | Basic operations versus n | Comparisons in a sort |
| Space complexity | Extra memory versus n | Auxiliary array, stack |
| Best case | Fewest steps | Sorted input to insertion sort |
| Worst case | Most steps | Reverse input to insertion sort |
| Average case | Expected steps | Random input |
Example 1.1: Counting operations in a loop
Problem: Count how many times the statement s = s + a[i] runs when summing an array of n elements, and find the extra space needed.
Solution:
- The loop runs for i = 0 to n−1, so the addition executes n times: T(n) = n.
- The initialisation
s = 0runs once and the loop test runs n + 1 times, but the dominant term is n. - Extra space: the variables s and i, so S(n) = 2 which does not grow: O(1).
Result: T(n) = n additions and constant extra space; for n = 1000 the statement runs 1000 times.
def total(a):
s, count = 0, 0
for x in a:
s += x
count += 1
return s, count
for n in (10, 100, 1000):
s, c = total(list(range(n)))
print(f"n={n:<5} sum={s:<7} additions={c}")
Output
n=10 sum=45 additions=10
n=100 sum=4950 additions=100
n=1000 sum=499500 additions=1000
Common mistakes
- Measuring seconds on one computer and calling that the algorithm's complexity.
- Counting every statement instead of the dominant basic operation.
- Quoting the best case as if it were typical behaviour.
- Forgetting that the recursion stack also uses space.
Key takeaways
- An algorithm has input, output, definiteness, finiteness and effectiveness.
- Apriori analysis counts steps as a function of n and is machine independent.
- Time complexity counts basic operations; space complexity counts extra memory.
- Worst case gives a guarantee; best and average cases give more detail.
Practice questions
- Name the five properties of an algorithm.
- What is the difference between apriori and posteriori analysis?
- Why is the worst case usually reported?
Answers to the practice questions
- Input, output, definiteness, finiteness and effectiveness.
- Apriori counts steps mathematically before coding; posteriori measures actual running time of a program.
- It is an upper limit that the algorithm never exceeds on any input of that size.
Sources
- Official BCA syllabus Design and Analysis of Algorithms, course code 26BCA404DS03, Unit I
