0

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?

Adrian Mole
52.1k193 gold badges61 silver badges100 bronze badges
asked Nov 1, 2020 at 18:04

1 Answer 1

1

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

answered Nov 1, 2020 at 18:56
2
  • How did you recive from (sum C, i = j to n) to (n - j + 1)? It should not be (n - j + 1)(n + j)? Thank you for your answer. Commented Nov 1, 2020 at 21:30
  • Since C is constant you factor it out then the inner sum becomes sum(i=j to n) of 1 which is (n-j+1). For example, sum(3 to 5) of 1 is 1+1+1=3=(5-3+1) Commented Nov 2, 2020 at 6:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.