Counting Sort
Counts how many times each value appears, without comparing numbers.
- Level
- Intermediate
- Topic:
- Sorting & searching
- Concepts:
- Input & output
- Arrays
- Para
- Randomness
- SubProcesos
Run, change and debug this example in your browser.
What you'll learn
Since the values go from 1 to 99, a conteo array stores how many times each one appears; then the array is rewritten by walking conteo in order. It never compares two numbers: it costs O(n + k), where k is the number of possible values. It's very fast when k is small, but it doesn't work when the values could be anything.
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 OrdenamientoConteo Definir datos, conteo, n, i, valor, veces, k 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) // Una casilla por cada valor posible (1 a 99): eso es la k de O(n + k) Dimension conteo[99] Para valor <- 1 Hasta 99 Hacer conteo[valor] <- 0 FinPara // Contamos cuántas veces aparece cada valor Para i <- 1 Hasta n Hacer conteo[datos[i]] <- conteo[datos[i]] + 1 FinPara // Reescribimos el arreglo: cada valor tantas veces como apareció k <- 0 Para valor <- 1 Hasta 99 Hacer // "Con Paso 1": si un valor no apareció, este Para no se ejecuta Para veces <- 1 Hasta conteo[valor] Con Paso 1 Hacer k <- k + 1 datos[k] <- valor FinPara FinPara MostrarDatos("Después: ", datos, n)FinAlgoritmoFlowchart
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: 20Antes: 84 96 41 50 83 97 85 7 67 26 39 94 95 4 40 19 71 4 2 76 Después: 2 4 4 7 19 26 39 40 41 50 67 71 76 83 84 85 94 95 96 97
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(n + k) |
| Average | O(n + k) |
| Worst | O(n + k) |
| Memory | O(k) |
Challenge
Show which value was repeated the most.
Show hint
Walk conteo looking for its maximum, the same way you'd find the largest value in an array.
Related examples
Bubble Sort
Sorts random numbers by swapping neighbors, and stops as soon as they're in order.
IntermediateSelection Sort
Finds the smallest of the remaining numbers and puts it in its place.
IntermediateInsertion Sort
Inserts each number among the sorted ones, like arranging cards in your hand.
Intermediate