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
  • 73,212
  • 30
  • 182
  • 400
Razor
  • 109
  • 1
  • 3

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
  • 82,470
  • 26
  • 145
  • 239