What Is An Algorithm?

 An Algorithm is simply a set of instructions to solve a problem. That's it. We use algorithms more often than we think. 

For example:

  • When following a recipe, you are using a cooking recipe. You are following a set of instructions to solve the problem of how to cook the food.

Let's look at a more programming related example. And as always this will be done in pseudocode.

Let's say we are given a list of [1,4,3] and we want to sort this list in increasing order.

Well approaches could we take to solve this? First we'll look at bubble sort.

Bubble Sort:

  • Check indices 0 & 1
  • if list at index 0 is larger than index 1, swap the values so that index 1(the smaller number) comes before index 2 (the larger number).
  • continue this process for index 1 & 2, 2 & 3 and so on 
  • check if the list is sorted, if not, run this process again
Bubble sort works, however can be very slow, in other words, have a very slow time complexity(how long it take an algorithm to solve the problem, represented as O(n).)

Lets look at an example of Bubble Sort at work.

[1,4,3]
//index 0 and 1 in order already, continue to 1 and 2
[1,3,4]
//sorted

Seems fast right? Well in this example yes, but what if we had a larger list? Lets try [1,5,3,7,3,8,3,8,3,7]

[1,5,3,7,3,8,3,8,3,7]
[1,3,5,7,3,8,3,8,3,7]
[1,3,5,3,7,8,3,8,3,7]
[1,3,5,3,7,3,8,8,3,7]
[1,3,5,3,7,3,8,3,8,7]
[1,3,5,3,7,3,8,3,7,8]
//not sorted, repeat
[1,3,3,5,7,3,8,3,7,8]
[1,3,3,5,3,7,8,3,7,8]
[1,3,3,5,3,7,3,8,7,8]
[1,3,3,5,3,7,3,7,8,8]
//not sorted, repeat
[1,3,3,3,5,7,3,7,8,8]
[1,3,3,3,5,3,7,7,8,8]
//not sorted, repeat
[1,3,3,3,3,5,7,7,8,8]
//Sorted!

Well that was very tedious to type out, but you can definitely see the significant difference. This is because the Bubble Sort Algorithm has a time complexity of O(n^2). n being the size of the list. Lets look at this mathematically for a better representation.


Here we have the graph O(n^2). As you can see, as the size of the list(n) increases, the time taken to solve the problem increases drastically.

Depending on your program, you could require an algorithm that can sort through a list of 50, 100, or even 1000 elements. There are many other algorithms that could work faster. I won't go over them here but feel free to look them up and try them out for yourself.




 

Sorting Algorithms:

  • Bubble Sort
  • Merge Sort
  • Insertion Sort
  • Heap Sort
  • Quick Sort










Comments

Popular posts from this blog

About Me

Introduction To Algorithms And Data Structures