The above function iterates through the sample_array a certain number of times, the size of the array is unknown to us at this point.
So we also want to know how much time does it take to run the above function, independent on various factors such as the processing power of the computer, the operating system, programming language, etc.
Letâs rather ask this question; âhow does the runtime of the function grow as the size of the input growsâ?
Well the more elements there are in a given array, the more elements there are to add up.
The question we just asked is answered by The Big O Notation and Time Complexity.
Big O notation is an industry standard for measuring efficiency and performance of your program based on four criteria:
- The ability to access a specific element within a data structure
- Searching for a particular element within a data structure
- Inserting an element into a data structure
- Removing an element from a data structure
Letâs say we need to store data which performs good at accessing elements quickly or a data structure that can add or delete elements easily, which do we use? Well we have the mathematical tool Big O notation to help us decide.
These four criteria accessing, searching, inserting and deleting are all sorted using Big O notation time complexity equations.
This works by inserting the size of the dataset as an integer n and in return we get the number of operations that need to be conducted by the computer before the function can finish.
The integer n represents the size of the data set/ the amount of elements contained within the data structure.
So if we have an array with size of 100 then n would be equal to 100, n=100.
We would place 100 into the different efficiency equations and returned to us would be the number of operations needed to be completed by the computer.
Determining The Time Complexity
Time complexity is a method used to show how the runtime of a function increases as the size of the input(n) increases.
How do we determine time complexity? Well we have two rules we use:
- Keep the fastest Growing Term
- Drop constants
Example:
Time = a*n+b
Letâs start with the first rule, we keep the fastest growing term which is a*n, b is our constant and thus we drop it.
Now we have Time = a*n and we implement our second rule stating that we must drop all constants, we are just left with one, which is a.
When we drop a we are left with Time = n, also referred to as Big O(n).
Big O Notation Time Complexity Types
There are six most common types of time complexity equations namely;
- O(1), O(n), O(logn), O(nlogn), O(n^2), O(2^n)
These vary from most efficient to least efficient, in this article we will only be discussing three of the six.
O(1)