1

So I have this code:

  done <- false                                     [1]
  n <- 0                                            [1]
  while (n < a) and (done = false)                  [(n+1)(1+1+1)]
    done <- true                                    [n]
    for m <- (a- 1) downto n                        [n(1+1+1+1)]
       if list[m] < list[m - 1] then                [n]
         tmp <- list[m]                             [n]
         list[m] <- list[m-1]                       [n]
         list[m - 1] <- tmp                         [n]
         done <- false                              [n]
       n <- n + 1                                   [1]
  return list                                       [1]

Am I doing this right? My conclusions are that the inne for-loop runs (n^2 + n) / 2 times and the outher while-loop runs n+1 times. I don't know how to properly argue for that the bubble sort has the complexity O(n^2)

Raphael
  • 72,336
  • 29
  • 179
  • 389
Badcoder
  • 11
  • 2
  • What does the column of square-bracketed terms mean? Is "n2" a typo for "n^2"? – David Richerby Jan 31 '14 at 14:07
  • It's the ''cost'' of the operations. I did them on the best case, should they be there for the worst case? I'm supposed to also find the constant and that's why they are there. And yes, it's a typo – Badcoder Jan 31 '14 at 14:11
  • We have many questions on similar problems, see e.g. [tag:loops]. – Raphael Jan 31 '14 at 14:20

1 Answers1

-2

There is just one loop in for, so the number of steps here will be proportional to n not n^2. The outer loop is running in a n proportional number of steps too. So The complexity of your algorithm is n^2.
N.B. : When speaking complexity, you don't have to state (n^2 + n) / 2,just say n^2 because they are the same for big ns.

mounaim
  • 101
  • 1
  • 2
    The number of steps in the inner loop being proportional to $n^2$ refers to the aggregate over all iterations of the outer loop. Also, $n^2$ is not the same as $\frac{n^2+n}2$, no matter how large $n$ might get. – FrankW Jan 31 '14 at 16:50