Overview
Data Structures
Searching
Bubble Sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. It continues this process until the entire array is sorted.
Although it's easy to understand, Bubble Sort is not efficient for large datasets due to its O(n²) time complexity.
// Bubble Sort in JavaScript
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
console.log(bubbleSort([5, 2, 9, 1, 5, 6])); // Output: [1, 2, 5, 5, 6, 9]Start with an empty array of a chosen length. New slots start as NULL — fill them with Push or Insert below.
Compares each adjacent pair, one step at a time, and swaps them if they're out of order.
Bubble Sort can be used in situations where the dataset is small and performance is not a critical factor.
For example, it's useful for teaching sorting concepts or when sorting a small number of items like organizing names alphabetically in a classroom list.
// Sorting student names alphabetically using Bubble Sort const names = ["Rita", "Amit", "Kunal", "Sneha"]; bubbleSort(names); console.log(names); // Output: ["Amit", "Kunal", "Rita", "Sneha"]