What’s Bubble Sort Doing Under the Hood?
Quick Fix Summary
Copy the ready-to-run JavaScript below, paste it into any browser console in Chrome, Firefox, or Edge (2026), and call bubbleSort([5, 2, 9, 1, 5]). The sorted array is returned in O(n²) time.
Bubble sort keeps making passes through your list, comparing neighbors side by side. Whenever two adjacent numbers are out of place, they swap spots. After enough passes, the biggest unsorted number “bubbles up” to its correct place at the end. Repeat this until a full round finishes with zero swaps—then you’re done.
How Do You Actually Build a Bubble Sort?
Below are ready-to-run snippets for JavaScript (Node.js 20 LTS or browser), Python 3.12+, and Java 21.
JavaScript (ES6+) – Works in Browser Console or Node
Hit F12 in Chrome 124, Firefox 125, or Edge 124 (as of 2026) to open DevTools, then flip to the Console tab.
// bubbleSort.js
function bubbleSort(arr) {
let swapped;
const n = arr.length;
do {
swapped = false;
for (let i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]; // destructuring swap
swapped = true;
}
}
} while (swapped);
return arr;
}
// Usage
console.log(bubbleSort([5, 2, 9, 1, 5])); // [1, 2, 5, 5, 9]
Python 3.12+ – Runs Anywhere Python 3.12+ Is Installed
Fire up any Python 3.12+ shell on Windows, macOS, or Linux.
def bubble_sort(arr):
n = len(arr)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i] # tuple swap
swapped = True
return arr
# Usage
print(bubble_sort([5, 2, 9, 1, 5])) # [1, 2, 5, 5, 9]
Java 21 (LTS) – Compile & Run
Save the code to BubbleSort.java, then run javac BubbleSort.java followed by java BubbleSort.
public class BubbleSort {
public static int[] bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
do {
swapped = false;
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return arr;
}
public static void main(String[] args) {
int[] data = {5, 2, 9, 1, 5};
int[] sorted = bubbleSort(data);
System.out.println(Arrays.toString(sorted)); // [1, 2, 5, 5, 9]
}
}
