0

I know this is easy but my textbook doesn't talk about Big-Oh order with do-while loops, and neither do any of my other algorithm sources.

This problem states that the following code fragment is parameterized on the variable "n", and that a tight upper bound is also required.

int i=0, j=0;

do {

    do {

          System.out.println("...looping...");  //growth should be measured in calls to println. 

          j=j+5;

       } while (j < n);

    i++;

    j = 0;

} while (i < n);

Can anyone help me with this and explain Big-Oh order in terms of do-while loops? Are they just the same as for loops?

Ryan Horner
  • 123
  • 1
  • 1
  • 7

1 Answers1

2

A good maxim for working with nested loops and big-O is

"When in doubt, work from the inside out!"

Here's the code you have posted:

int i=0, j=0;
do {
    do {
          Do something
          j=j+5;
    } while (j < n);
    i++;
    j = 0;
} while (i < n);

Let's look at that inner loop. It runs roughly n / 5 times, since j starts at 0 and grows by five at each step. (We also see that j is always reset back to 0 before the loop begins, either outside the loop or at the conclusion of an inner loop). We can therefore replace that inner loop with something that basically says "do Θ(n) operations that we care about," like this:

int i=0;
do {
    do Θ(n) operations that we care about;
    i++;
} while (i < n);

Now we just need to see how much work this does. Notice that this will loop Θ(n) times, since i counts 0, 1, 2, ..., up to n. The net effect is that this loop is run Θ(n) times, and since we do Θ(n) operations that we care about on each iteration, the net effect is that this does Θ(n2) of the printouts that you're trying to count.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065