What is the time complexity of fun()?

`int` `fun(` `int` `n) ` `{ ` ` ` `int` `count = 0; ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `for` `(` `int` `j = i; j > 0; j--) ` ` ` `count = count + 1; ` ` ` `return` `count; ` `} ` |

*chevron_right*

*filter_none*

**(A)** Theta (n)

**(B)** Theta (n^2)

**(C)** Theta (n*Logn)

**(D)** Theta (nLognLogn)

**Answer:** **(B)** **Explanation:** The time complexity can be calculated by counting number of times the expression “count = count + 1;” is executed. The expression is executed 0 + 1 + 2 + 3 + 4 + …. + (n-1) times.

Time complexity = Theta(0 + 1 + 2 + 3 + .. + n-1) = Theta (n*(n-1)/2) = Theta(n^{2})

Quiz of this Question

## Recommended Posts:

- Analysis of Algorithms | Big-O analysis
- Algorithms | Analysis of Algorithms (Recurrences) | Question 1
- Algorithms | Analysis of Algorithms (Recurrences) | Question 2
- Algorithms | Analysis of Algorithms | Question 1
- Algorithms | Analysis of Algorithms (Recurrences) | Question 3
- Algorithms | Analysis of Algorithms | Question 3
- Algorithms | Analysis of Algorithms | Question 4
- Algorithms | Analysis of Algorithms | Question 5
- Algorithms | Analysis of Algorithms | Question 19
- Algorithms | Analysis of Algorithms | Question 19
- Algorithms | Analysis of Algorithms (Recurrences) | Question 4
- Algorithms | Analysis of Algorithms | Question 8
- Algorithms | Analysis of Algorithms | Question 9
- Algorithms | Analysis of Algorithms | Question 10
- Algorithms | Analysis of Algorithms | Question 11
- Algorithms | Analysis of Algorithms | Question 12
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 6
- Algorithms | Analysis of Algorithms | Question 13
- Algorithms | Analysis of Algorithms (Recurrences) | Question 7