Selection Sort
Finds the smallest of the remaining numbers and puts it in its place.
- Level
- Intermediate
- Topic:
- Sorting & searching
- Concepts:
- Input & output
- Arrays
- Para
- Si
- Randomness
- SubProcesos
Run, change and debug this example in your browser.
What you'll learn
On round i it looks for the smallest value between positions i and n and moves it to position i with a single swap. It always scans everything that's left, so it makes about n²/2 comparisons even if the data is already sorted: O(n²) in every case, but at most n - 1 swaps.
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 OrdenamientoSeleccion Definir datos, n, i, j, minimo, aux, intercambios Como Entero 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) intercambios <- 0 // "Con Paso 1" evita que el Para cuente hacia atrás cuando n = 1 Para i <- 1 Hasta n - 1 Con Paso 1 Hacer // Buscamos el menor entre las posiciones i y n minimo <- i Para j <- i + 1 Hasta n Hacer Si datos[j] < datos[minimo] Entonces minimo <- j FinSi FinPara // Y lo llevamos a la posición i con un solo intercambio Si minimo <> i Entonces aux <- datos[i] datos[i] <- datos[minimo] datos[minimo] <- aux intercambios <- intercambios + 1 FinSi FinPara MostrarDatos("Después: ", datos, n) Escribir "Intercambios realizados: ", intercambiosFinAlgoritmoFlowchart
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: 68 56 75 80 18 35 34 44 6 37 11 41 Después: 6 11 18 34 35 37 41 44 56 68 75 80 Intercambios realizados: 9
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:Not stableIn place
Challenge
Also count the comparisons and check them against n * (n - 1) / 2.
Show hint
Add 1 to a counter right before the Si that compares datos[j] with datos[minimo].
Related examples
Linear vs. Binary Search
Counts the comparisons each search needs on the same sorted list.
IntermediateShell Sort
Insertion sort between far-apart elements, with a gap that shrinks every pass.
AdvancedMerge Sort
Splits the array in halves, sorts each one recursively and merges them.
Advanced