0

I'm given a pseodocode statement as such:

function testFunc(B)
  for j=1 to B.length-1
     for i=1 to B.length-j
       if(B[i-1] > B[i]
         swap B[i-1] and B[i]

And I'm told to show that this algorithm runs in Big o O(n^2) time.

So I know that the first for loop runs n times, because I believe it's inclusive. I'm not sure about the rest of the lines though, would the second for loop run n-2 times? Any help would be much appreciated.

user3739406
  • 254
  • 1
  • 3
  • 16
  • Let's say b.length (n) = 5, so j = 1,2,3,4,5. Then It's (for the second for loop), 1<= 4, 2<=3, 3<=2, then it exits, since n = 5, that's 2 times less, so n-2 times? – user3739406 Oct 21 '15 at 00:12

3 Answers3

1

The inner loop runs a decreasing number of times. Look at a concrete example. If B.length were 10, then the contents of the inner loop would be executed 10 times, then 9 times, and so on, down to 1 time.

Using Gauss' equation of:

n(n + 1) / 2

you can see that the inner code would be executed 55 times in that example. (10(10 + 1)/2 = 55)

So, it follows that for n times, it would run n(n + 1) / 2 times. This is equivalent to:

1/2 n^2 + 1/2 n

In terms of Big-Oh, the co-efficients and the smaller values of n are ignored, so this is equivalent to O(n^2).

1

If N = B.length, then outer loop runs N-1 times, and inner loop runs (N-1)+...+3+2+1 times, for a total of (N-1) * (N/2) = N^2/2 - N/2 times, which means O(n^2).

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • How Does the outer loop execute n-1 times? Is there a difference between "execute" and "run". I was shown an example from **i=1 to array.length-1** and was told that that executes n times. – user3739406 Oct 21 '15 at 00:35
  • @user3739406 If `array.length` is 2, then it's `i = 1 to 2-1` aka `i = 1 to 1`, so it only loops once. – Andreas Oct 21 '15 at 03:30
1

Let's say that B.length is 5 times. The outer loop will thus run 4 times. On the first iteration through the outer loop, the inner loop will run 4 times; on the second iteration the inner loop will run 3 times; 2 times for the third iteration; and 1 time for the fourth.

Let's lay the results out geometrically:

AAAA
AAA
AA
A

Each A represents getting to the conditional/swap inside the nested loop, and you want to know, in general, how many A's there are. An easy way to count them is to double the triangle shape to produce a rectangle:

AAAAB
AAABB
AABBB
ABBBB

and you can quickly see that for a triangle whose side is length N, there are N*(N-1)/2 A's because they are half of the N*(N-1) rectangle is made up of A's. Carrying out the multiplication, and ignoring the scale factor of 1/2 (because big-O doesn't care about constants), we see that there are O(N^2) A's.

pjs
  • 18,696
  • 4
  • 27
  • 56