Sorting Algorithms

How Bubble Sort Works

  • Waiting
  • Being compared
  • Just moved
  • In final position
1/102

Bubble sort, 12 values in random order.

Settings

More options
Starting order

Two to 48 numbers, used in the order you type them.

Bubble Sort

  1. 1for i in 0..n-1:
  2. 2 swapped = false
  3. 3 for j in 0..n-i-2:
  4. 4 if a[j] > a[j+1]:
  5. 5 swap(j, j+1)
  6. 6 swapped = true
  7. 7 // a[n-1-i] is now final
  8. 8 if not swapped: break

How the Seven Compare

AlgorithmBestAverageWorstExtra memoryStable
BubbleO(n)O(n²)O(n²)O(1)Yes
InsertionO(n)O(n²)O(n²)O(1)Yes
SelectionO(n²)O(n²)O(n²)O(1)No
ShellO(n log n)O(n√n)O(n²)O(1)No
MergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuickO(n log n)O(n log n)O(n²)O(log n)No
HeapO(n log n)O(n log n)O(n log n)O(1)No

Scroll the table sideways for the rest of the columns.

Stable means equal values keep their original order.