
How to Write an Algorithm: A friendly guide with examples
In this guide we will learn how to write an algorithm. Algorithms play an important role in solving problems in today’s technology-driven world. Whether you’re developing software, automating tasks, or improving decision-making processes, algorithms serve as a blueprint for problem solving. Although the term “algorithm” may sound technical and intimidating at first, writing an algorithm is something you can quickly get to grips with a little practice.
In this comprehensive guide, we’ll explain what an algorithm is, the steps you need to take to write an algorithm, and show you how to apply these principles to your projects using real-world examples. We’ll break it down in a way that’s easy for you to follow, whether you’re just starting out or want to brush up on your skills. So let’s get started!
Table of Contents:
- What is an algorithm?
- The steps to writing an algorithm
- Understanding pseudocode: The bridge between ideas and code
- Real world examples of algorithms
- Optimizing your algorithms: Efficiency and performance
- Common algorithm pitfalls and how to avoid them
- Final thoughts: Keep practicing
1. what is an algorithm?
Basically, an algorithm is a step-by-step procedure or formula to solve a problem. It’s like a recipe: you follow certain instructions to achieve the desired result. The key difference is that algorithms focus on computational or logical tasks, whereas recipes are about preparing a delicious meal!
An algorithm helps to break down a complex problem into smaller, more manageable steps. For example, consider the task of sorting a list of numbers. You could sort the list by hand, but an algorithm provides a systematic way to ensure the task is done correctly and efficiently every time.
Main features of algorithms:
- Input: Data provided to the algorithm.
- Output: The result that results from the algorithm.
- Definiteness: Each step of the algorithm must be clear and unambiguous.
- Finiteness: An algorithm should have a finite number of steps and deliver a result at the end.
- Effectiveness: The steps should be feasible and solve the problem in a reasonable time.
By the end of this guide, you will have the confidence to write your own algorithms from scratch. But before we move on to the examples, let’s outline the process of creating a good algorithm.
2. How to write an algorithm: steps
Writing an algorithm is not just a matter of throwing a few steps together. You need to think through the problem carefully and break it down into logical components. Let’s take a look at the individual steps:
Step 1: Understand the problem
Before you start writing, you need to fully understand the problem. What are you trying to solve? What data or input do you have, and what result do you need?
For example, imagine you are asked to write an algorithm that calculates the grade point average of students in a class. The inputs are the individual grades of the students, and the output should be the average grade.
Step 2: Planning the approach
Once you understand the problem, you need to decide how to approach it. At this point plan the sequence of steps. Think logically about what actions you need to take to achieve the desired result.
In our example, the sequence could look like this:
- Step 1: Add up all the points.
- Step 2: Count how many students there are.
- Step 3: Divide the total number of points by the number of students to get the average.
Step 3: Write the steps in detail
Now it’s time to write down each step clearly. This is a bit like writing instructions for someone who has no idea what you’re talking about. Be specific, clear and direct.
For our grade point average example:
- Start by initializing a variable that contains the sum of the scores.
- Loop through the list of scores and add each score to the total.
- Count the total number of students.
- Divide the total by the number of students.
- Output the result (the average).
Step 4: Test your algorithm
Even the best algorithm does not work perfectly the first time. That’s why it’s important to test your algorithm. Run it with different inputs, even in borderline cases (e.g. when there is only one student or no students at all), to make sure it behaves as expected.
Step 5: Optimizing the algorithm
After you have written and tested your algorithm, you should consider whether it can be made more efficient. Could it run faster? Could it use less memory? This step is about improving the performance of your algorithm without changing its functionality.
3. Understanding pseudocode: The bridge between ideas and code
Before you dive into programming, you should use pseudocode — a method to write down the steps of your algorithm in simple language without worrying about the syntax of a programming language. Pseudocode helps you focus on the logic of your algorithm without getting bogged down in the details of programming.
Example of pseudocode:
Let’s take the student average example again, but this time write it in pseudocode:
1. Start with a total score of 0.
2. For each student:
a. Add the student's score to the total score.
3. Count the number of students.
4. Calculate the average by dividing the total score by the number of students.
5. Give the average.
Pseudocode does not follow strict programming rules, but it lays the foundation for you to start writing real code. Once you have written pseudocode, the next step is to convert it into a specific programming language.
4. How to write an algorithm: Real world examples
To get a clearer picture of how algorithms work in real-world applications, let’s go through a few examples that start with simple ones and gradually become more complex.
Example 1: Searching for the largest number in a list
Imagine you have a list of numbers and you want to find the largest number. This is what the algorithm could look like in pseudocode:
Pseudocode:
1. Set the largest number to the first number in the list.
2. For each number in the list:
a. If the number is greater than the current largest number, update the largest number.
3. Output the largest number.
Code in Python:
python def find_largest_number(numbers):
largest = numbers [0] # Start with the first number
for number in numbers:
if number > largest:
largest = number
return largest
Example 2: Sorting a list (bubble sort)
Sorting algorithms are a classic example in computer science. One of the simplest sorting algorithms is bubble sort , which repeatedly runs through the list, compares neighbouring elements and swaps them if they are in the wrong order.
- Repeat the process for each element in the list:
a. For each pair of adjacent elements:
i. If the first element is larger than the second, swap them. - Stop when no more swaps are needed.
Code in Python:
python def bubble_sort(numbers):
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
return numbers
Example 3: Checking for prime numbers
You may need an algorithm to check whether a certain number is a prime number. A prime number is a number greater than 1 that has no divisors other than 1 and itself.
Pseudocode:
- If the number is less than 2, return False.
- For any number between 2 and the square root of the number:
a. If the number is evenly divisible, return False. - If no divisors are found, return True.
Code in Python:
python import math
def is_prime(number):
if number < 2:
return False
for i in range(2, int(math.sqrt(number))) + 1):
if number % i == 0:
return False
return True
—
5. How to write an algorithm: Optimising for Efficiency and performance
When writing algorithms, it’s important to think about efficiency, especially for tasks that involve large data sets or require fast results. The efficiency of an algorithm is often measured by its time complexity (how long it takes to execute) and memory complexity (how much memory it requires).
Big O notation
The most common way to express the efficiency of an algorithm is the **Big O notation**, which describes how the runtime or memory requirement grows with the size of the input. Here is a brief overview of the common Big O terms:
– O(1):Constant time. The algorithm takes the same amount of time regardless of the size of the input.
– O(n):Linear time. The runtime increases proportionally with the size of the input.
– O(n^2): Quadratic time. The runtime increases with the square of the input size.
– O(log n):Logarithmic time. The runtime increases slowly compared to the size of the input.
Example for the optimization of a search algorithm
Let’s say you have an unsorted list of numbers and need to find a specific number. A simple approach would be to search each number in a loop and compare it to the target number (O(n) time overhead). However, if the list is sorted, you can use the binary search, which is much faster (O(log n) time).
Here is the algorithm for the binary search:
Pseudocode:
- Start with two pointers, one at the beginning and one at the end of the list.
- The two pointers must not overlap:
a. Calculate the center of the list.
b. If the midpoint is the target, return the midpoint.
c. If the center point is smaller than the target, move the start pointer to the center point + 1.
d. If the center point is greater than the target, move the end pointer to the center point – 1. - If the target is not found, return -1.
Code in Python:
python def binary_search(numbers, target):
start = 0
end = len(numbers) - 1
while start <= end:
mid = (start + end) // 2
if numbers[mid] == target:
return mid
elif numbers[mid] < target:
start = mid + 1
otherwise:
end = mid - 1
return -1
The binary search on a sorted list makes the algorithm much more efficient than a simple linear search.
6. Common algorithm pitfalls and how to avoid them
Writing algorithms is not always easy. There are a few common pitfalls you may encounter. Here are some to watch out for and how to avoid them:
- Unclear problem definition: If you don’t fully understand the problem before you start writing the algorithm, you’re likely to run into obstacles. Take time to clarify the problem before you start.
- Overcomplicating the solution: Sometimes we get so busy trying to come up with a clever solution that we overlook simpler approaches. Always try to find a simple solution first.
- Ignore edge cases: Algorithms should be tested for all possible scenarios, including edge cases (e.g. empty lists, negative numbers or very large inputs). Do not assume that your algorithm will work for every case until you have tested it thoroughly.
- Do not consider efficiency: Especially with large amounts of data, an inefficient algorithm can lead to significant delays or crashes. Always consider the time and space complexity of your solution.
7. Final thoughts: Keep practicing!
Writing algorithms can seem daunting at first, but like any skill, it gets easier with time. Start by solving simple problems and gradually work your way up to more complex problems. Use pseudocode to plan your approach and always test your algorithms with different inputs.
Remember that the best way to improve is through practice. Try writing algorithms for everyday problems you encounter, such as sorting a shopping list, calculating the best route to a destination or organizing a to-do list. These small exercises will strengthen your skills and increase your self-confidence.
Good luck and have fun writing algorithms!

