I’m just studying for my data structures & algorithms final. The following question was on my midterm and I got it wrong, so I’m just trying to figure it out:
What is the complexity of the following pseudocode?
x <- 0 for x <- 0 to n: for y <- 0 to n: y <- y + 1 y <- y * 2
On the midterm I answered O( n^2 ) but now that I’m looking at it again, I think it might be O( nlogn ).. See my answer below showing my attempt.
What is the correct answer?
Any help is helping me pass my exam!
Cheers!
The following is my answer for the moment…
The outer loop
for x <- 0 to nexecutes n times, definitely.The inner loop
for y <- 0 to nappears to execute n times, however every time it executes, its contained code brings y exponentially closer to n. So I believe that this section of code executes with O( logn ) complexity.Thus, the whole algorithm executes with O( nlogn ) time complexity.