Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
This algorithm is easy to understand and implement, but it is not very efficient for large datasets compared to more advanced sorting algorithms like Quick Sort or Merge Sort. Bubble Sort is mainly useful for learning purposes and small collections.
Bubble Sort works by comparing pairs of adjacent elements:
Because it repeatedly scans the array, the time required grows quickly as the array size increases.
function bubbleSort(arr) {
const result = [...arr];
for (let i = 0; i < result.length; i++) {
for (let j = 0; j < result.length - 1 - i; j++) {
if (result[j] > result[j + 1]) {
// Swap values
const temp = result[j];
result[j] = result[j + 1];
result[j + 1] = temp;
}
}
}
return result;
}
// Example usage
const values = [5, 2, 9, 1, 5, 6];
console.log(bubbleSort(values)); // [1, 2, 5, 5, 6, 9]