Different algorthims have the different time complexities its based on their code,in time complexities we often use the log functions,but so many dont know when to use the log functions in the time complexity.Let me give a clear idea about the using of the log functions in the Time complexities.
we use the log functions when the function is multiplied by a factor or divisible by factor or adding or subtraction but not in linear form.I see it is very difficult to explain lets take a example each thing i say above
example1:
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
}
}
the above two for loops are the linear functions , so the time complexity of the above lines of code is the O(n^2)
Example2:
in this example we usage of the log functions in the code
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j=j*2)
{
}
}
in the first for loop, the function is in the form of linear so its complexity is O(n),but the second for loop is not in linear form ,the j gets multiplied by 2 every time,in this case we use the log functions ,the total time complexity of above code is O(n log n)
Example3:
in this example we usage of the log functions in the code
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j=j/2)
{
}
}
in the first for loop, the function is in the form of linear so its complexity is O(n),but the second for loop is not in linear form ,the j gets divided by 2 every time,in this case we use the log functions ,the total time complexity of above code is O(n log n)
Example4:
in this example we usage of the log functions in the code
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j=j+2)
{
}
}
in the first for loop, the function is in the form of linear so its complexity is O(n),but the second for loop is not in linear form ,the j gets added by 2 every time,in this case we use the log functions ,the total time complexity of above code is O(n log n)
Example5:
in this example we usage of the log functions in the code
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j=j-2)
{
}
}
in the first for loop, the function is in the form of linear so its complexity is O(n),but the second for loop is not in linear form ,the j gets subtractd by 2 every time,in this case we use the log functions ,the total time complexity of above code is O(n log n)
These are possibilities in getting log functions in their Time complexity .Lets take a real algorithm as a example,Merge sort algorithm has log functions in their log functions,in the algorithm it has to divide the arrays into two arrays every time to solve ,so array is getting divided by 2 every time .so its contains the log functions.The time complexity of the Merge Sort is the O(n log n)
No comments:
Post a Comment