Bubble sort
Easy TimeO(n²) SpaceO(1)
Given an array arr of numbers, sort it into ascending order in place, exchanging only values that sit next to each other. Equal neighbours are never exchanged, which is what keeps the sort stable.
Examples
Example 1
- Input
- arr = [5, 2, 8, 1, 4]
- Output
- The same five values, ascending.
[1,2,4,5,8]
Example 2
- Input
- arr = [1, 2, 3]
- Output
- Already in order: 3 comparisons and not one exchange.
[1,2,3]
The Code
function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
const tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
return arr;
}
bubbleSort([5, 2, 8, 1, 4]);Done
The first 18 calls, of 20. This one does not fit on a page.
More like this
All sorting examples (8) →- Merge sort Divide and conquer — split in half, sort, then merge.
- Quick sort Pick a pivot, partition around it, recurse on each side.
- Insertion sort Grow a sorted prefix, inserting each new item into place.
- Selection sort Find the smallest remaining element and swap it into place.
- Counting sort No comparisons — tally each value, then read the tallies back out.
- Heap sort Build a max-heap, then repeatedly move the root to the back.