|
|
|
|
|
for i = 1:n,
for j = n:i+1, if a[j] < a[j-1], swap a[j,j-1]
invariant: a[1..i] in final position
if no swaps this iteration, stop
end
Bubble sort has many of the same properties as insertion sort, but has slightly higher overhead. In the case of nearly sorted data, bubble sort takes O(n) time, but requires at least 2 passes through the data (whereas insertion sort requires something more like 1 pass).
to restart the animations.
Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.