In: Computer Science
What is the Θ( ) for each code segment below?
(a) for( int i = 1, i<= n, i = i*2){
some constant operation
}
(b) for( int i = 1, i<= n, i++){
for( int j = 2*i, j<=n, j++){
some constant operation
}
}
(c) for( int i = 1, i<= n, i = i*2){
for( int j = 1, j<=n, j = j*2){
some constant operation
}
}
This code has one loops Values of i during first loop are from 1,2,4,8,..,n So, First loop running for log(n) times Time complexity = O(Number of times loop runs) = O(log(n)) =========================================== This code has two loops Values of i during first loop are from 1,2,3,..,n So, First loop running for n times Values of j during first loop are from 2*i,2*i+1,,..,n So, Second loop running for n-2i times So, in worst case second loop running for n times Time complexity = O(Product of number of times both loop runs) = O(n*n) = O(n^2) =========================================== This code has two loops Values of i during first loop are from 1,2,4,8,..,n So, First loop running for log(n) times Values of j during first loop are from 1,2,4,8,..,n So, Second loop running for log(n) times Time complexity = O(Product of number of times both loop runs) = O(log(n)*log(n)) = O(log(n)^2)