This post shows how to implement Bubble Sort in JavaScript — the simplest sorting algorithm to learn, and a common first step before moving on to more efficient algorithms like merge sort or quick sort.
Bubble sort in JavaScript:
Explanation:
Bubble sort repeatedly steps through the array, comparing each pair of adjacent elements and swapping them if they're in the wrong order. Each full pass "bubbles" the largest remaining element to its correct position at the end, so after n passes, the array is fully sorted. It's easy to understand but inefficient for large arrays.
See Bubble Sort in Action
Drag the slider to scrub through every comparison and swap step by step, or use Play to watch it run automatically.
JavaScript Program to Implement Bubble Sort
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
const numbers = [64, 25, 12, 22, 11];
console.log("Sorted array:", bubbleSort(numbers));
Output:
Sorted array: [ 11, 12, 22, 25, 64 ]
Bubble sort is a good starting point, but it's rarely used in production — once you're comfortable with it, see how Merge Sort and Quick Sort improve on it. Practice more in our Code Runner.
Frequently Asked Questions About Bubble Sort in JavaScript
What is the time complexity of bubble sort?
Bubble sort runs in O(n²) time in the average and worst case, since it uses nested loops to repeatedly compare and swap adjacent elements. Its best case (already sorted input, with an early-exit optimization) is O(n).
Why is bubble sort rarely used in real applications?
Its O(n²) time complexity makes it far slower than algorithms like merge sort or quick sort on large datasets. It's primarily taught for its simplicity and as a foundation for understanding more advanced sorting algorithms.
Is bubble sort a stable sorting algorithm?
Yes. Bubble sort only swaps adjacent elements when one is strictly greater than the next, so equal elements retain their original relative order.
