0

I have been doing a little reading up on bubble sort and have read on wikipedia that it's complexity is measured as $\Theta(n^2)$

This bubble sort however is slightly more efficient. I thought this would be the best place to ask how I would work out this particular implementations complexity seeing that the number of iterations in the inner loop is reduced with each pass.

for (top = items.Length; top > 0; top--)
            {
                for (low = 0, high = 1; high < top; low++, high++)
                {
                    if (items[low].CompareTo(items[high]) > 0)
                    {
                        tmp = items[high];
                        items[high] = items[low];
                        items[low] = tmp;
                    }
                }
            }
Raphael
  • 72,336
  • 29
  • 179
  • 389
Razor
  • 109
  • 1
  • 3
  • 1
    What have you tried? Where did you get stuck? Have you checked any of the myriad similar questions on here? (search "runtime loop"). – Raphael Dec 05 '13 at 23:06
  • Well my logic was that if there were 10 items, then there would be 100 operations in total. But that wouldn't be the case if the inner loop decreased with each outer loop. – Razor Dec 06 '13 at 00:56

1 Answers1

3

The inner loop is executed $(n-1) + (n-2) + (n-3) + \dots + 0 = \tfrac{1}{2}n(n-1) = \Theta(n^2)$ times.

David Richerby
  • 81,689
  • 26
  • 141
  • 235