Algoritmos de Ordenamiento

Bubble Sort (Burbuja) Paso a Paso

Comparación de adyacentes, burbujeo y complejidad O(N²) en C, Java, JavaScript y Python.

SLIDE 1 / 6

1. Mecánica de Burbujeo

Bubble Sort compara pares de elementos adyacentes e intercambia sus posiciones si están en orden incorrecto. El elemento mayor "burbujea" hasta el final de la lista en cada pasada.

ANÁLISIS ALGORÍTMICO
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. Simulador

Visualización espacial 3D del burbujeo de barras en tiempo real:

Array: [5, 2, 8, 1, 4]
Hacé clic en "Siguiente Paso" o "Auto Play" para iniciar el ordenamiento 3D.
Estado: Listo