简体   繁体   中英

What will be the time complexity of this algorithm by frequency count method?

Following is the code:

for (i = n-1; i>0; i--)
    for (j=0; j<i; j++)
      if (arr[i] < arr[i+1])
      {
          temp = arr[i];
          arr[i] = arr[i+1];
          arr[i+1] = temp;
      }

I could find for the outer for outer for loop will execute n times and the inner for loop will be executed i+i-1+i-2+....+1 i(i+1)/2=(i^2+i)/2 and the if condition will be checked for (i-1)*i/2=(i^2-i)/2 times but I am confused for the statements in if condition and also correct me if I am wrong for the my above calculations too.

for n = 5, the values of i and j encountered when the if statement is executed can be listed as follows:

(4,0) (4,1) (4,2) (4,3)
(3,0) (3,1) (3,2)
(2,0) (2,1)
(1,0)

I arranged the items like that on purpose because they form a triangle.

####
###
##
#

To count how many items are in this triangle we can mirror the triangle and count each item twice. There are two ways to do it neatly depending on whether you place the mirrored items to the right or below.

####o
###oo
##ooo
#oooo
####
###o
##oo
#ooo
oooo

Either way, by inspecting width times height , this can easily be seen to be a rectangle of either n * (n-1) or (n-1) * n items (equal area in both cases). And since we counted each element twice, we can divide by two, and use (n-1) * n / 2 as the formula for the number of items.

Therefore your if condition will be computed exactly (n-1) * n / 2 times.

You also correctly expanded this expression to be ((n*n) - (n)) / 2 which is also equal to (n^2 - n) / 2 .

But a few things were bad...

You said (i-1)*i/2 , using i instead of n . That's not right.

Your code appears to intend to compute a Bubble sort . And the index for the if condition and its block should be j (not i ) throughout. (You were comparing arr[i] to arr[i+1] for the same value of i repeatedly in the inner loop. The actual swap would be evaluated at most once for a given value of i , in that case, or not at all, depending on the values of arr .)

The code you intended was likely:

for (i = n-1; i>0; i--)
    for (j=0; j<i; j++)
      if (arr[j] < arr[j+1])
      {
          temp = arr[j];
          arr[j] = arr[j+1];
          arr[j+1] = temp;
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM