In the previous chapter, we took a look at our first data structures and saw how choosing the right data structure can affect the performance of our code. Even two data structures that seem so similar, such as the array and the set, can have very different levels of efficiency.
In this chapter, we’re going to discover that even if we decide on a particular data structure, another major factor can affect the efficiency of our code: the proper selection of which algorithm to use.
Although the word algorithm sounds like something complex, it really isn’t. An algorithm is simply a set of instructions for completing a specific task.
Even a process as simple as preparing a bowl of cereal is technically an algorithm, as it involves following a defined set of steps to achieve the task at hand. The cereal-preparation algorithm follows these four steps (for me, at least):
By following these steps in this particular order, we can now enjoy our breakfast.
When applied to computing, an algorithm refers to the set of instructions given to a computer to achieve a particular task. When we write any code, then, we’re creating algorithms for the computer to follow and execute.
We can also express algorithms using plain English to set out the details of the instructions we plan on providing the computer. Throughout this book, I’ll use both plain English as well as code to show how various algorithms work.
Sometimes, it’s possible to have two different algorithms that accomplish the same task. We saw an example of this at the beginning of Chapter 1, , where we had two different approaches for printing out even numbers. In that case, one algorithm had twice as many steps as the other.
In this chapter, we’ll encounter another two algorithms that solve the same problem. In this case, though, one algorithm will be faster than the other by orders of magnitude.
To explore these new algorithms, we’ll need to take a look at a new data structure.