An algorithm is a set of well-defined instructions to solve a particular problem. The simplest real-world analogy is following a recipe:
We have a set of ingredients to prepare a dish. We carefully follow the recipe and execute the steps in a sequence. The end result is a tasty dish.
For example, we have a cup of noodles, a tastemaker, and water as the ingredients. For the recipe, we have steps:
- Boil water
- pour water into the cup
- Add tastemaker
- Close the lid and wait 5 minutes.
The output is a cup of tasty noodles, that you can enjoy. Let’s extend this to computer programming.
Consider an algorithm to add two numbers. In this case, we refer to the ingredients as inputs, the recipe as an algorithm, and the recipe as output.
- In our scenario input will be two numbers a and b.
- The algorithm steps include
1. Add the numbers using the ‘+’ operator.
2. Return the value.
- The output is the sum of the two numbers.
Hopefully, now you can understand what an algorithm is.
Why should we learn algorithms?
As a developer, you are going to come across problems that you need to solve. When you learn or practice algorithms, you’re basically learning different techniques to efficiently solve those problems. We can solve a problem in many ways using different algorithms. And every algorithm comes with its own tradeoffs when it comes to performance.