Understanding of Asymptotic Notation

Whenever we solve any problem there is a sequence of steps that needs to be followed. We have already read the term algorithm, which is nothing but a sequence of steps to achieve the result. Our algorithm took some time and space to solve it.
The running time depends upon several factors:-
  • Single/Multiple processor system.
  • R/W speed to memory.
  • CPU speed.
  • 32/64 bit system.
  • Input Size.
Do we really need all the factors to calculate the time complexity? Don't you think the hardware couldn't be a factor in the time calculation of the algorithm? Let's understand this in more detail.
For example, Kavya and I are working on the problem that needs us to calculate the sum of n natural numbers. We come up with a different-2 approach to solve the problem. Now, Kavya has an i7 machine and running the code, it takes less than 1 ms and I have a dual-core machine that takes 5ms and there is a huge possibility that when I run the same code in a high configuration machine then it might take up less time than Kavya's algorithm.
We don't need to bother about all these hardware-related factors in the time analysis algorithm. We consider only the input size along with how our program will behave with respect to the rate of growth in input?
To calculate the time complexity we use asymptotic notation which is a mathematical way of representation. Asymptotic notation is not perfect but it is the best way to analyze the time complexity of the algorithm. With the help of the asymptotic notation, we can easily find out which algorithm is better.
There are three cases to analyze the algorithm using asymptotic notation.
  • O - "Big-Oh" notation
  • Ω - "Big-Omega" notation
  • Θ - "Big-Theta" notation
We will be discussing all the cases in more detail in the upcoming blogs. This would be a solution to the aforementioned problem in this blog with step by step calculation.
Supposedly we have to sum the first n natural numbers then what would our approach be?

Approach 1:-

    public int sum(int n) {
        int sum = 0; // O(1) constant time
        for (int i = 1; i <= n; i++) { // O(n+1) +1 is for termination the loop
            sum+=i; // O(n) adding value of current i to previous calucate sum
        }
        return sum; // O(1) returning the value 
    }

Approach 2:-

    public int sum(int n) {
        return n* (n+1)/2; // O(1) constant time.
    }
We can easily guess the time complexity of approach 1 is O(n) linear time and approach 2 is O(1) constant time. We will see the rules of the time complexity calculation.

Comments

Popular posts from this blog

Recursion

Stack

Data Structure & Algorithm