# Algorithms | Analysis of Algorithms | Question 8

What is the time complexity of the below function?

## C

 `void` `fun(``int` `n, ``int` `arr[])` `{` `    ``int` `i = 0, j = 0;` `    ``for` `(; i < n; ++i)` `        ``while` `(j < n && arr[i] < arr[j])` `            ``j++;` `}`

(A)

O(n)

(B)

O(n2)

(C)

O(n*log(n))

(D)

O(n*log(n)2)

Explanation:

At first look, the time complexity seems to be O(n2) due to two loops. But, please note that the variable j is not initialized for each value of variable i. So, the inner loop runs at most n times. Please observe the difference between the function given in the question and the below function:

## C

 `void` `fun(``int` `n, ``int` `arr[])` `{` `    ``int` `i = 0, j = 0;` `    ``for` `(; i < n; ++i) {` `        ``j = 0;` `        ``while` `(j < n && arr[i] < arr[j])` `            ``j++;` `    ``}` `}`

Quiz of this Question
Please comment below if you find anything wrong in the above post

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next