开发者

data structure - running time

开发者 https://www.devze.com 2023-01-14 01:50 出处:网络
Just a confusion.... A portion of a C++ sample code is as follows I just re-edit the whole post. Sorry for any confusion

Just a confusion.... A portion of a C++ sample code is as follows


I just re-edit the whole post. Sorry for any confusion

int i, j;   
i = 0;    // c1
j = 0;    // c2
while (i < n)   // (n+1)c3
{
  i++;   // n c4
   while ( j < i) 开发者_JS百科 // (2+3+....+n+(n+1)c5
   {
     j++;   // (1+2+...+n)c6
   }
  j = 0;  // c7
}

Clearly, c1, c2, and c7 are constant. We are not interested in those, and they don't really matter in determing the running time.

What I don't understand is c5 and c6.

Why is it 2+3+4...+n+(n+1) for c5? Why does it start with 2, instead of 1+2+3...+(n+1)??? Note that we can rewrite C5 -> (n*(n-1)/2) + n

For c6, this cominbation can be rewritten as n*(n-1)/2

Initially I thought C6 is n, because C6 depends on two conditions, the first while and second while loop. But since j will always go back to 0, so we are really depending on the first while loop. Because n < n is false, then the j++ wil run maxiumly n-th time.

n = 3

0 < 3, 1, 0 < 1, 1, 0

1 < 3, 2, 0 < 1, 1, 0

2 < 3, 3, 0 < 1, 1, 0

3 < 3 fail.

Can someone please explicitly explain how C5 and C6 are deteremined? I am sorry if this problem sound dumb to the experts Thank you!


Here, you have a running time of 2n. Everytime i is incremented, j is one smaller, so the inner loop is executed exactly once.

i=0, j=0 // init
i=1, j=0 // outer loop
i=1, j=1 // inner loop
i=2, j=1 // outer loop
i=2, j=2 // inner loop

More typically, you'd reset j to 0 in the outer loop. In that case, you'd have a runtime of n*(n-1)/2


I don't entirely understand your question but it seems to me that you need to move the initialization of j inside the loop:

while (i < n)   
{
    j = 0;    // <--- here
    i++;   
    // etc...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消