![]() |
VOOZH | about |
The analysis of loops for the complexity analysis of algorithms involves finding the number of operations performed by a loop as a function of the input size. The following are the general steps to analyze loops for complexity analysis:
O(1) refers to constant time means that the running time of an algorithm remains constant and does not depend on the size of the input. A loop or recursion that runs a constant number of times is also considered O(1). For example, the following loop is O(1).
Example : Swap function
The Time Complexity is O(n) if the loop variables are incremented/decremented by a constant amount. For example, searching for an element in an unsorted array or iterating through an array and performing a constant amount of work for each element.
The time complexity is defined as an algorithm whose performance is directly proportional to the squared size of the input data, as in nested loops it is equal to the number of times the innermost statement is executed.
Example:Selection sort and Insertion Sort have O(n2) time complexity.
The time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount.
Example:Binary Search(refer iterative implementation) has O(Logn) time complexity.
The Time Complexity of a loop is considered as O(Log Log n) if the loop variables are reduced/increased exponentially by a constant amount.
See this for mathematical details.
When there are consecutive loops, we calculate time complexity as a sum of the time complexities of individual loops. For example, consider the following code:
As discussed here, the worst-case time complexity is the most useful among best, average and worst. Therefore we need to consider the worst case.