Steps:
Run the algorithm to see the recorded steps.
Steps:
Run the algorithm to see the recorded steps.
Bubble Sort is a simple sorting algorithm that repeatedly walks through the list to be sorted, comparing each pair of adjacent elements and swapping them if they are in the wrong order. This process is repeated until the list is sorted. The name 'Bubble Sort' comes from the fact that larger elements 'bubble' to the top of the list with each iteration.
Complexity: In the classic version, the time complexity is always O(n²) in all scenarios (worst, average, and best case). Since this algorithm has no early-stop mechanism, even if the list is already completely sorted (best case), it will still perform all passes and comparisons in a 'blind' way, wasting processing time.
1const bubbleSort = (arr) => {
2 // Outer loop ensures the sweep happens N times
3 for (let i = 0; i < arr.length; i++) {
4 // Inner loop ignores the last already sorted elements
5 for (let j = 0; j < arr.length - i - 1; j++) {
6 // If the current is greater than the next, swap!
7 if (arr[j] > arr[j + 1]) {
8 let temp = arr[j];
9 arr[j] = arr[j + 1];
10 arr[j + 1] = temp;
11 }
12 }
13 }
14 return arr;
15};Bubble Sort is a simple sorting algorithm that repeatedly walks through the list to be sorted. It compares each pair of adjacent elements and swaps them if they are in the wrong order. The process is repeated until the entire list is sorted. The name 'Bubble Sort' comes from the fact that larger elements 'bubble' to the end of the list with each iteration.
Although it is one of the most famous and studied algorithms in programming, Bubble Sort is rarely implemented in production systems, real-world software, or standard libraries. Its quadratic nature O(n²) makes it extremely slow as the amount of data grows. Its main value is didactic: it is the perfect tool to introduce students to sorting concepts, array iteration, and performance analysis, serving as an essential foundation for understanding more efficient algorithms.