Skip to content
ExamplesEspañolWorkspace →

Counting Sort

Counts how many times each value appears, without comparing numbers.

Level
Intermediate
Concepts:
Input & output
Arrays
Para
Randomness
SubProcesos
Open in Codoritmo

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

counting-sort.psc · 43 lines
// 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)FinAlgoritmo

Flowchart

Each block in the flowchart matches one instruction in the code.

Algoritmo OrdenamientoConteo
Algoritmo OrdenamientoConteoAlgoritmo OrdenamientoConteoAlgoritmo OrdenamientoConteoDefinir datos, conteo, n, i, valor, veces, k Como EnteroDefinir datos, conteo, n, i,valor, veces, k Como EnteroEscribir "¿Cuántos números quieres ordenar? (1 a 512)"Escribir "¿Cuántos númerosquieres ordenar? (1 a 512)"Leer nLeer nDimension datos[n]Dimension datos[n]Para i <- 1 Hasta n HacerPara i <- 1 Hasta ndatos[i] <- Aleatorio(1, 99)datos[i] <- Aleatorio(1, 99)MostrarDatos("Antes: ", datos, n)MostrarDatos("Antes: ",datos, n)Dimension conteo[99]Dimension conteo[99]Para valor <- 1 Hasta 99 HacerPara valor <- 1 Hasta 99conteo[valor] <- 0conteo[valor] <- 0Para i <- 1 Hasta n HacerPara i <- 1 Hasta nconteo[datos[i]] <- conteo[datos[i]] + 1conteo[datos[i]] <-conteo[datos[i]] + 1k <- 0k <- 0Para valor <- 1 Hasta 99 HacerPara valor <- 1 Hasta 99Para veces <- 1 Hasta conteo[valor] Con Paso 1 HacerPara veces <- 1 Hastaconteo[valor] Con Paso 1k <- k + 1k <- k + 1datos[k] <- valordatos[k] <- valorMostrarDatos("Después: ", datos, n)MostrarDatos("Después: ",datos, n)FinAlgoritmoFinAlgoritmo
SubProceso MostrarDatos
SubProceso MostrarDatosSíNoSubProceso MostrarDatos(titulo, datos, n)SubProceso MostrarDatos(titulo,datos, n)Definir i Como EnteroDefinir i Como EnteroSi n <= 30 Entoncesn <= 30Escribir Sin Saltar tituloEscribir Sin Saltar tituloPara i <- 1 Hasta n HacerPara i <- 1 Hasta nEscribir Sin Saltar datos[i], " "Escribir Sin Saltar datos[i]," "Escribir ""Escribir ""Escribir titulo, n, " números (el primero es ", datos[1], " y el último ", datos[n], ")"Escribir titulo, n, " números(el primero es ", datos[1], "y el último ", datos[n], ")"FinSubProcesoFinSubProceso

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.

Complexity
CaseCost
BestO(n + k)
AverageO(n + k)
WorstO(n + k)
MemoryO(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.

Open in Codoritmo
  • Bubble Sort

    Sorts random numbers by swapping neighbors, and stops as soon as they're in order.

    Intermediate
  • Selection Sort

    Finds the smallest of the remaining numbers and puts it in its place.

    Intermediate
  • Insertion Sort

    Inserts each number among the sorted ones, like arranging cards in your hand.

    Intermediate