Bubble sort: Difference between revisions
No edit summary |
|||
(4 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
[[Category:Videos]] | |||
{{#ev:youtube|https://www.youtube.com/watch?v=gTCYd7rmbIc|500|right|Bubble sort|frame}} | |||
== General Information == | == General Information == | ||
'''Algorithmic problem:''' [[Sorting based on pairwise comparison]] | '''Algorithmic problem:''' [[Sorting based on pairwise comparison]] | ||
Line 40: | Line 42: | ||
== Complexity == | == Complexity == | ||
'''Statemen:''' The asymptotic complexity is in <math>\Theta(n^2)</math> in the best and worst case. | '''Statemen:''' The asymptotic complexity is in <math>\Theta(T\cdot n^2)</math> in the best and worst case, where <math>T</math> is the complexity of the comparison. | ||
'''Proof:''' The asymptotic complexity of the inner loop in the <math>i</math>-th iteration of the outer loop is in <math>\Theta(n - i)</math>. Therefore, the total complexity is in <math>\Theta \left( \sum_{i=1}^{n-1} (n-i) \right) = \Theta \left( \sum_{i=1}^{n-1} i \right) = \Theta \left( \frac{n(n-1)}{2}\right) = \Theta(n^2)</math> | '''Proof:''' The asymptotic complexity of the inner loop in the <math>i</math>-th iteration of the outer loop is in <math>\Theta(T\cdot(n - i))</math>. Therefore, the total complexity is in <math>\Theta \left( T\cdot\sum_{i=1}^{n-1} (n-i) \right) = \Theta \left( T\cdot\sum_{i=1}^{n-1} i \right) = \Theta \left( T\cdot\frac{n(n-1)}{2}\right) = \Theta(T\cdot n^2)</math> |
Latest revision as of 22:50, 19 June 2015
General Information
Algorithmic problem: Sorting based on pairwise comparison
Type of algorithm: loop
Abstract View
Invariant: After
Variant:
Break condition:
Induction Basis
Abstract view: Nothing to do.
Implementation: Nothing to do.
Proof: Nothing to show.
Induction Step
Abstract view: Step-by-step, move the maximum element seen so far to the position
Implementation: For
Correctness: The loop invariant of the inner loop is this: after
Pseudocode
BUBBLESORT(A)
1 for i = 1 to "A.length" - 1
2 for j = A.length downto i + 1
3 if A[j] < A[j - 1]
4 exchange A[j] with A[j - 1]
Complexity
Statemen: The asymptotic complexity is in
Proof: The asymptotic complexity of the inner loop in the