« Back to full matrix

Animated Sorting Algorithm Demo: Bubble Sort

Size:  20 · 30 · 40 · 50 ·
Algorithm:  Insertion · Selection · Bubble · Shell · Merge · Heap · Quick · Quick3

Algorithm

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
        

Properties

Discussion

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).

Directions

Key

References

Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.