Search code examples
algorithmtimetime-complexitycomplexity-theory

Time complexity of nested for-loop with two independent variables


I am trying to calculate the time complexity of this function:

int fun1(A, k){      //A is an array, k is an integer
n = length(A);       //length of array
for j:= 1 to k{
    for i:= j to n{
        if A[i] < A[j-1]{
            x:=  A[j-1]; 
            A[j-1]:= A[i]; 
            A[i]:= x
        }
    }
}
return A[k-1]}

We iterate k times in the outer loop, but how to calculate number of iterations of inner loop, and then the time complexity of entire algorithm?


Solution

  • Since the work inside the double loop is constant and assuming that k<=n then the complexity can be written as

    enter image description here

    Edit: I forgot the constant but it doesn't matter as it will disappear inside the big Oh notation