Bubble Sort Step by Step
Adjacent comparison, bubbling, and O(N²) complexity in C, Java, JS, and Python.
SLIDE 1 / 6
1. Bubbling Mechanics
Bubble Sort repeatedly compares adjacent elements swapping them if out of order. The largest element bubbles up to the end in each pass.
ALGORITHMIC ANALYSIS
Peor Caso / PromedioO(N²)
Mejor Caso (Optimizado con flag)O(N)
Espacio AuxiliarO(1) in-place
2. C: Bubble Sort In-Place
Implementación clásica con punteros o arreglos y variable auxiliar de swap.
bubble.c
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} 3. Java: Optimización con Flag swapped
Si en una pasada no se realiza ningún intercambio, el arreglo ya está ordenado y podemos cortar tempranamente.
BubbleSort.java
public static void bubbleSort(int[] arr) {
boolean swapped;
for (int i = 0; i < arr.length - 1; i++) {
swapped = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp;
swapped = true;
}
}
if (!swapped) break;
}
} 4. JavaScript: Destructuring Swap
JS permite intercambiar dos posiciones usando sintaxis de desestructuración `[a, b] = [b, a]`.
bubble.js
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;
} 5. Python: Tuple Swapping
Python realiza el intercambio de elementos en una sola línea `arr[j], arr[j+1] = arr[j+1], arr[j]`.
bubble.py
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr 6. Simulator
Real-time 3D spatial visualization of bubbling bars:
Array: [5, 2, 8, 1, 4]
Hacé clic en "Siguiente Paso" o "Auto Play" para iniciar el ordenamiento 3D.
Estado: Listo
Navigation: Left / Right Arrows