We talked about what an algorithm is in the previous sections, but not all algorithms are made equal and it is our job to consider the patterns and features that allow us to find the best solutions for our problems.
Consider sorting data into alphabetical order as an example.
We could choose to use Bubble Sort, or Insertion Sort – but which should we choose and why?
In this example we could look at how long it would take to run the algorithm. Although computers can run code lightening fast, it’s still important to make sure that our programs are efficient because as they grow an inefficient algorithm can mean a slow program.
But what is efficiency? Just like efficient electricity, we are looking for something that uses less – but instead of less electricity, we want an algorithm that uses less time or memory.
With smaller programs it’s difficult to tell how much time is being used. Instead of running your algorithm as code, try instead to “dry run” your algorithm instead. Dry running is writing out the values that are held in your variables into a table before you write a single line of code. If you are trying to get an idea of how long it will take to run your sorting algorithms, this will give you a clear idea.
You can also get an idea of how long your algorithm will take by considering how many times it loops. In the Bubble Sort, there is an outer loop and an inner loop meaning that if the inner loop repeated 5 times, and the outer loop repeated 5 times, the inner loop would in fact repeat 5 * 5 times = 25 times!
How would this compare to the Insertion sort? What would the maximum number of ‘swaps’ be compared to Bubble Sort? You can find out more about sorting here.