Bubble Sort
Sorts random numbers by swapping neighbors, and stops as soon as they're in order.
- Level
- Intermediate
- Topic:
- Sorting & searching
- Concepts:
- Input & output
- Arrays
- Para
- Mientras
- Si
- Logic
- Randomness
- SubProcesos
Run, change and debug this example in your browser.
What you'll learn
Each pass compares neighbors and swaps them when they're out of order, so the largest one "bubbles up" to the end. If a pass makes no swaps, everything is already sorted and the Mientras loop ends early. That's why it costs O(n) when the data comes sorted and O(n²) on average and in the worst case.
Code
// Muestra el arreglo completo solo si es corto (30 o menos)SubProceso MostrarDatos(titulo, datos, n) Definir i Como Entero Si n <= 30 Entonces Escribir Sin Saltar titulo Para i <- 1 Hasta n Hacer Escribir Sin Saltar datos[i], " " FinPara Escribir "" SiNo Escribir titulo, n, " números (el primero es ", datos[1], " y el último ", datos[n], ")" FinSiFinSubProcesoAlgoritmo OrdenamientoBurbuja Definir datos, n, i, j, aux, pasadas Como Entero Definir huboCambios Como Logico Escribir "¿Cuántos números quieres ordenar? (1 a 512)" Leer n Dimension datos[n] Para i <- 1 Hasta n Hacer datos[i] <- Aleatorio(1, 99) FinPara MostrarDatos("Antes: ", datos, n) // En cada pasada, el mayor "sube" hasta su lugar al final pasadas <- 0 huboCambios <- Verdadero Mientras huboCambios Y pasadas < n - 1 Hacer pasadas <- pasadas + 1 huboCambios <- Falso Para j <- 1 Hasta n - pasadas Hacer Si datos[j] > datos[j + 1] Entonces aux <- datos[j] datos[j] <- datos[j + 1] datos[j + 1] <- aux huboCambios <- Verdadero FinSi FinPara // Si una pasada no cambió nada, el arreglo ya está ordenado FinMientras MostrarDatos("Después: ", datos, n) Escribir "Pasadas necesarias: ", pasadasFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
¿Cuántos números quieres ordenar? (1 a 512)User answer: 12Antes: 18 31 82 57 10 74 26 85 29 44 60 91 Después: 10 18 26 29 31 44 57 60 74 82 85 91 Pasadas necesarias: 6
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(n) |
| Average | O(n²) |
| Worst | O(n²) |
| Memory | O(1) |
Traits:StableIn place
Challenge
Sort the numbers from largest to smallest.
Show hint
Changing the comparison operator inside the Si is enough.
Related examples
Insertion Sort
Inserts each number among the sorted ones, like arranging cards in your hand.
IntermediateShell Sort
Insertion sort between far-apart elements, with a gap that shrinks every pass.
AdvancedHeap Sort
Arranges the array as a heap, then takes the largest out again and again.
Advanced