Algorithms · interactive · step by step
Sorting Algorithm Visualizer
Watch bubble, insertion, selection, merge, quick, heap, shell, counting and radix sort step by step, with the pseudocode line, comparisons and swaps, and a race of all nine on the same list.
Comparisons 0Writes 0compare swap/write pivot sorted
Step 0Space play · ←→ step
Reference
Sorting algorithm time complexity
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Shell sort | O(n log n) | about O(n^1.3) | O(n²) | O(1) | No |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes |
| Radix sort (LSD) | O(d·(n + 10)) | O(d·(n + 10)) | O(d·(n + 10)) | O(n + 10) | Yes |
Code
Sorting algorithms in Python, JavaScript, C++ and Java
Bubble sort
Python
def bubble_sort(a):
for end in range(len(a) - 1, 0, -1):
swapped = False
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
if not swapped:
break
return aJavaScript
function bubbleSort(a) {
for (let end = a.length - 1; end > 0; end--) {
let swapped = false;
for (let i = 0; i < end; i++) {
if (a[i] > a[i + 1]) { [a[i], a[i + 1]] = [a[i + 1], a[i]]; swapped = true; }
}
if (!swapped) break;
}
return a;
}C++
void bubbleSort(std::vector<int>& a) {
for (int end = a.size() - 1; end > 0; --end) {
bool swapped = false;
for (int i = 0; i < end; ++i)
if (a[i] > a[i + 1]) { std::swap(a[i], a[i + 1]); swapped = true; }
if (!swapped) break;
}
}Java
static void bubbleSort(int[] a) {
for (int end = a.length - 1; end > 0; end--) {
boolean swapped = false;
for (int i = 0; i < end; i++)
if (a[i] > a[i + 1]) { int t = a[i]; a[i] = a[i + 1]; a[i + 1] = t; swapped = true; }
if (!swapped) break;
}
}Insertion sort
Python
def insertion_sort(a):
for i in range(1, len(a)):
j = i
while j > 0 and a[j] < a[j - 1]:
a[j], a[j - 1] = a[j - 1], a[j]
j -= 1
return aJavaScript
function insertionSort(a) {
for (let i = 1; i < a.length; i++)
for (let j = i; j > 0 && a[j] < a[j - 1]; j--) [a[j], a[j - 1]] = [a[j - 1], a[j]];
return a;
}C++
void insertionSort(std::vector<int>& a) {
for (size_t i = 1; i < a.size(); ++i)
for (size_t j = i; j > 0 && a[j] < a[j - 1]; --j) std::swap(a[j], a[j - 1]);
}Java
static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++)
for (int j = i; j > 0 && a[j] < a[j - 1]; j--) { int t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; }
}Selection sort
Python
def selection_sort(a):
for i in range(len(a) - 1):
m = min(range(i, len(a)), key=a.__getitem__)
a[i], a[m] = a[m], a[i]
return aJavaScript
function selectionSort(a) {
for (let i = 0; i < a.length - 1; i++) {
let min = i;
for (let j = i + 1; j < a.length; j++) if (a[j] < a[min]) min = j;
[a[i], a[min]] = [a[min], a[i]];
}
return a;
}C++
void selectionSort(std::vector<int>& a) {
for (size_t i = 0; i + 1 < a.size(); ++i)
std::swap(a[i], *std::min_element(a.begin() + i, a.end()));
}Java
static void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) if (a[j] < a[min]) min = j;
int t = a[i]; a[i] = a[min]; a[min] = t;
}
}Merge sort
Python
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]JavaScript
function mergeSort(a) {
if (a.length <= 1) return a;
const mid = a.length >> 1;
const left = mergeSort(a.slice(0, mid)), right = mergeSort(a.slice(mid));
const out = [];
while (left.length && right.length) out.push(left[0] <= right[0] ? left.shift() : right.shift());
return [...out, ...left, ...right];
}C++
void mergeSort(std::vector<int>& a, int lo, int hi) {
if (hi - lo < 1) return;
int mid = (lo + hi) / 2;
mergeSort(a, lo, mid); mergeSort(a, mid + 1, hi);
std::inplace_merge(a.begin() + lo, a.begin() + mid + 1, a.begin() + hi + 1);
}Java
static void mergeSort(int[] a, int lo, int hi) {
if (hi - lo < 1) return;
int mid = (lo + hi) / 2;
mergeSort(a, lo, mid); mergeSort(a, mid + 1, hi);
int[] t = new int[hi - lo + 1];
int i = lo, j = mid + 1, k = 0;
while (i <= mid && j <= hi) t[k++] = a[i] <= a[j] ? a[i++] : a[j++];
while (i <= mid) t[k++] = a[i++];
while (j <= hi) t[k++] = a[j++];
System.arraycopy(t, 0, a, lo, t.length);
}Quick sort
Python
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return a
pivot, i = a[hi], lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
quick_sort(a, lo, i - 1)
quick_sort(a, i + 1, hi)
return aJavaScript
function quickSort(a, lo = 0, hi = a.length - 1) {
if (lo >= hi) return a;
const pivot = a[hi]; let i = lo;
for (let j = lo; j < hi; j++) if (a[j] < pivot) { [a[i], a[j]] = [a[j], a[i]]; i++; }
[a[i], a[hi]] = [a[hi], a[i]];
quickSort(a, lo, i - 1); quickSort(a, i + 1, hi);
return a;
}C++
void quickSort(std::vector<int>& a, int lo, int hi) {
if (lo >= hi) return;
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; ++j) if (a[j] < pivot) std::swap(a[i++], a[j]);
std::swap(a[i], a[hi]);
quickSort(a, lo, i - 1); quickSort(a, i + 1, hi);
}Java
static void quickSort(int[] a, int lo, int hi) {
if (lo >= hi) return;
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; j++) if (a[j] < pivot) { int t = a[i]; a[i] = a[j]; a[j] = t; i++; }
int t = a[i]; a[i] = a[hi]; a[hi] = t;
quickSort(a, lo, i - 1); quickSort(a, i + 1, hi);
}Heap sort
Python
def heap_sort(a):
def sift(i, size):
while True:
big, l, r = i, 2 * i + 1, 2 * i + 2
if l < size and a[l] > a[big]: big = l
if r < size and a[r] > a[big]: big = r
if big == i: return
a[i], a[big] = a[big], a[i]
i = big
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift(i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift(0, end)
return aJavaScript
function heapSort(a) {
const sift = (i, size) => {
for (;;) {
let big = i; const l = 2 * i + 1, r = l + 1;
if (l < size && a[l] > a[big]) big = l;
if (r < size && a[r] > a[big]) big = r;
if (big === i) return;
[a[i], a[big]] = [a[big], a[i]]; i = big;
}
};
for (let i = (a.length >> 1) - 1; i >= 0; i--) sift(i, a.length);
for (let end = a.length - 1; end > 0; end--) { [a[0], a[end]] = [a[end], a[0]]; sift(0, end); }
return a;
}C++
void heapSort(std::vector<int>& a) {
std::make_heap(a.begin(), a.end());
std::sort_heap(a.begin(), a.end());
}Java
// java.util.PriorityQueue is a binary heap:
static int[] heapSort(int[] a) {
var pq = new java.util.PriorityQueue<Integer>();
for (int v : a) pq.add(v);
for (int i = 0; i < a.length; i++) a[i] = pq.poll();
return a;
}Shell sort
Python
def shell_sort(a):
gap = len(a) // 2
while gap > 0:
for i in range(gap, len(a)):
j = i
while j >= gap and a[j] < a[j - gap]:
a[j], a[j - gap] = a[j - gap], a[j]
j -= gap
gap //= 2
return aJavaScript
function shellSort(a) {
for (let gap = a.length >> 1; gap > 0; gap >>= 1)
for (let i = gap; i < a.length; i++)
for (let j = i; j >= gap && a[j] < a[j - gap]; j -= gap) [a[j], a[j - gap]] = [a[j - gap], a[j]];
return a;
}Counting sort
Python
def counting_sort(a):
count = [0] * (max(a) + 1)
for v in a:
count[v] += 1
return [v for v, c in enumerate(count) for _ in range(c)]JavaScript
function countingSort(a) {
const count = new Array(Math.max(...a) + 1).fill(0);
for (const v of a) count[v]++;
return count.flatMap((c, v) => Array(c).fill(v));
}Radix sort (LSD)
Python
def radix_sort(a):
exp = 1
while max(a) // exp > 0:
buckets = [[] for _ in range(10)]
for v in a:
buckets[v // exp % 10].append(v)
a = [v for b in buckets for v in b]
exp *= 10
return aJavaScript
function radixSort(a) {
for (let exp = 1; Math.floor(Math.max(...a) / exp) > 0; exp *= 10) {
const buckets = Array.from({ length: 10 }, () => []);
for (const v of a) buckets[Math.floor(v / exp) % 10].push(v);
a = buckets.flat();
}
return a;
}Questions
Sorting Algorithm Visualizer FAQ
Free, private and works offline: everything runs in your browser.
Which sorting algorithm is the fastest?
For general data, O(n log n) algorithms like merge sort, quick sort and heap sort beat O(n²) ones like bubble, insertion and selection sort once the list is more than a few dozen items. Quick sort is usually fastest in practice. For small whole numbers, counting and radix sort run in linear time. The race table under the visualizer counts comparisons and writes for every algorithm on your list: on 38, 27, 43, 3, 9, 82, 10, merge sort uses 14 comparisons and bubble sort 20.
What does stable sorting mean?
A stable sort keeps equal items in their original order. It matters when you sort by one field after another, such as sorting people by age after sorting by name. Bubble, insertion, merge, counting and radix sort are stable; selection, quick, heap and shell sort are not.
Why is insertion sort fast on nearly sorted data?
Each item only moves past the few items that are out of place, so a nearly sorted list takes close to n steps instead of n². Choose “Nearly sorted” to see it; that is why real-world sorts like Timsort use insertion sort for short runs.
How does quick sort work?
Pick a pivot (here the last item), move everything smaller to its left and everything larger to its right, so the pivot lands in its final place. Then sort the two sides the same way. On already sorted data this simple pivot choice gives the worst case, O(n²); real libraries pick a random or median pivot.
How does merge sort work?
Split the list in half, sort each half (by splitting again), then merge the two sorted halves by repeatedly taking the smaller front item. It always takes O(n log n) time but needs O(n) extra space for merging.
Can I sort my own numbers?
Yes. Type or paste up to 100 numbers separated by commas or spaces and press Use these numbers. The link updates so you can share the exact list and algorithm.