0% encontró este documento útil (0 votos)
125 vistas9 páginas

Algoritmo Counting Sort en C++

Este documento describe el método de ordenamiento Counting Sort. Explica que cuenta el número de elementos de cada clase para ordenarlos, y solo funciona para elementos contables como números enteros. Describe las etapas del algoritmo como encontrar el rango de los datos, crear un vector auxiliar para contar las apariciones de cada elemento, y luego recorrer este vector para obtener los elementos ordenados. También menciona las ventajas como una complejidad de O(n+k) y que es eficiente en el mejor y peor caso, pero sus desventajas son que requiere memoria ad
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
125 vistas9 páginas

Algoritmo Counting Sort en C++

Este documento describe el método de ordenamiento Counting Sort. Explica que cuenta el número de elementos de cada clase para ordenarlos, y solo funciona para elementos contables como números enteros. Describe las etapas del algoritmo como encontrar el rango de los datos, crear un vector auxiliar para contar las apariciones de cada elemento, y luego recorrer este vector para obtener los elementos ordenados. También menciona las ventajas como una complejidad de O(n+k) y que es eficiente en el mejor y peor caso, pero sus desventajas son que requiere memoria ad
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd

UNIVERSIDAD NACIONAL MICAELA

BASTIDAS DE APURIMAC

ESCUELA PROFESIONAL
DE INGENIERIA
DE INFORMATICA Y SISTEMAS

ASIGNATURA: Algorítmica ll

DOCENTE: [Link] CARI INCAHUANACO

TEMA: Método de Ordenamiento Counting Short

INTEGRANTES:
Este trabajo es dedicado
a mi grupo por esforzarse ,poner
empeño en este proyecto.
INDICE

1. Introducción……………………………………Pag. 4

2. Historia………………………………………….Pag. 5

3. Marco Teórico…………………………………Pag. 5

3.1 Tipos de ordenamientos……………Pag. 4

[Link] de Ordenamiento Counting Short………Pag. 5

5. Pseudocódigo………………………………………...pag6

[Link] en c++………………………………………….pag7

[Link].- …………………………………...............Pag. 9
METODO DE ORDENAMIENTO POR CUENTAS

(COUNTING SORT)
Introducción:
El algoritmo de ordenamiento Counting Sort (Ordenamiento por Cuentas en
español) es un algoritmo de ordenamiento en el que se cuenta el número de
elementos de cada clase para luego ordenarlos. Sólo puede ser utilizado por tanto
para ordenar elementos que sean contables, por ejemplo, los números enteros de
un determinado intervalo, sin contar números [Link] algoritmo fue creado por
Harold H. Seward en 1954.

El algoritmo es muy interesante por que no necesita ningún uso de una condición
a excepción de los bucles, tiene un mejor funcionamiento con una lista larga, de
un solo elemento simple (no hay estructuras),y de números repetitivos .
Es mejor que los numero no se separen entre si ,un ejemplo seria el valor máximo
sea de 15 y el mínimo de uno, aunque tengamos 10mil entradas (o elementos), la
desventaja de este algoritmo es la necesidad de almacenar muchos datos de
memoria.

Tipos de ordenamientos:

Los 2 tipos de ordenamientos que se pueden realizar son: los internos y los

Externos.

-Los internos:

Son aquellos en los que los valores a ordenar están en memoria principal,
por lo que se asume que el tiempo que se requiere para acceder cualquier
elemento sea el mismo (a[1], a[300], etc.).

-Los externos:

Son aquellos en los que los valores a ordenar están en memoria secundaria
(disco, cinta, cilindro magnético, etc.), por lo que se asume que el tiempo
que se requiere para acceder a cualquier elemento depende de la última
posición accesada (posición 1, posición 300, etc.).
Counting sort:
1: Análisis.-
Paso 1: consiste en averiguar cuál es el intervalo en que se encuentran los datos
a ordenar valores mínimo y máximo.
Paso 2: luego creamos un vector de números enteros tantos como valores haya
en el intervalo (mínimo, máximo) y cada elemento se le da un valor de cero (0).
Paso 3: tras esto se recorren todos los elementos a ordenar y se cuenta el número
de apariciones de cada elemento (usando el vector que hemos creado).
Paso 4: por ultimo basta con recorrer este vector para tener todos los elementos
ordenados.
-consideremos el siguiente ejemplo:
Lista a ordenar: 2 5 3 2 8 5 3 2
1.-buscar el mínimo y el máximo:
Mínimo=2
Máximo=8

2.-creamos un vector auxiliar :


Auxiliar=vector[2…8] que pertenecen alos enteros.

3.-Recorrer la lista de elementos y contar los elementos:


Al final, Auxiliar= [3, 2,0,2,0,0,1]
Auxiliar [2] =3 por que el valor 2 aparece 3 veces.
Auxiliar [7] = 0 por que el valor 7 no aparece en la anterior secuencia.

4.- * Recorriendo el vector auxiliar obtenemos la lista de números ordenada

Lista ordenada = 2 ,2 ,2 ,3 ,3 ,5 ,5 ,8

Un modo de hacer este algoritmo más práctico, es guardar varios elementos en un


índice de la matriz, pero en este caso la matriz ya no es de valores enteros sino
que contiene algún tipo de estructura de datos. Así es posible por ejemplo ordenar
números con decimales.
Por ejemplo si en la matriz auxiliar en el índice 5, metemos todas las apariciones
de la lista cuyo valor está en el rango 5.0 - 5.99. Luego con cada elemento en
cada índice se realiza un nuevo ordenamiento. cuando se usan este tipo de
técnicas, el algoritmo ya se considera otro, denominado: bucketsort.
Tiempo total: Σ O(n+k)

VENTAJAS:
-El algoritmo tiene una complejidad de O(N+k), siendo “n” el número de elementos
a ordenar y “k” el tamaño del vector auxiliar (Max-min).
-La eficiencia del algoritmo esta entre el mejor y peor caso.

DESVENTAJAS:
-El algoritmo como y ya sabemos no requiere de un condicional (if), pero requiere
de una memoria adicional .
- lento.
-solo ordena números enteros.
-mayormente se usa en arreglos en los q los números se repiten.
2.-Pseudocódigo:
Inicio
Variables(A[15],B[15 ],C[100],j,k,n,i)
//ingresamos la dimensión
leer dimension:n
Hacer para i=1 hasta n
Leer A[i]
si(A[i] > k)
k = A[i];
finsi
me=A[i]
finhacer
hacer para i=1 hasta n
si(me>A[i])
me=A[i];
finsi
finhacer
hacer para i=me hasta k
C[i]=0
finhacer

hacer para j=1 hasta n


C[A[j]]=C[A[j]]+1
finhacer

hacer para j=me hasta k


C[i+1] = C[i+1] + C[i];
Finhacer
hacer para j=n hasta 1
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
finhacer
escribir(“los elementos son:”)
hacer para i=1 hasta n
escribir(B[i])
finhacer

3.código en c++
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
int n,k = 0, A[15],me,total;
int i, j;
int B[15], C[100];
cout << "ingrese la cantidad d elementos : ";
cin >> n;
cout << "\ningrese los elementos :\n";
for ( int i = 1; i <= n; i++)
{
cin >> A[i];
if(A[i] > k)
{
k = A[i];
}
me=A[i];
}
for ( int i = 1; i <= n; i++)
{
if(me>A[i])
{
me=A[i];
}
}
for(i = me; i <= k; i++)
C[i] = 0;
for(j =1; j<=n; j++)
{C[A[j]] = C[A[j]] + 1;}

for(i =me; i<= k; i++)


C[i+1] = C[i+1] + C[i];
for(j = n; j >= 1; j--)
{
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
cout << "\nlos elementos son : ";
for(i = 1; i <= n; i++)
cout << B[i] << " " ;
getch();
}

Bibliografía:
BIBLIOGRAFIA
[Link]

[Link]
q=counting+sort+cormen&source=bl&ots=BwVsEE-

[Link]
denamiento

Common questions

Con tecnología de IA

The implementation steps for the Counting Sort algorithm based on the pseudocode are: 1) Determine the range of input values by finding the minimum and maximum. 2) Create an auxiliary array to hold counts of each input value within the range. 3) Initialize the auxiliary array with zeros. 4) Traverse the input array to tally occurrences of each value in the auxiliary array. 5) Modify the auxiliary array to store cumulative counts, which effectively transform it into an index map for the final sorted order. 6) Traverse the input array again, placing each element into its sorted position in the output array based on the auxiliary array's cumulative counts .

Counting Sort achieves its time complexity of O(n + k) through its linear traversal of the input array to tally occurrences and subsequent use of the auxiliary array to arrange elements. n corresponds to the number of elements, and k represents the range of input values, as each element is counted and indexed in a separate pass. The primary factors influencing this complexity are the size of the input array (n) combined with the range of possible values (k), emphasizing optimal performance when the range is relatively small and close to the number of elements .

Using a vector auxiliary in Counting Sort enhances its functionality by enabling the management of occurrences of elements across a range, facilitating sorting without comparisons. This vector structure allows direct access to counts of specific elements, which is particularly beneficial for sorting large datasets with integer elements where frequencies are concentrated within a specific interval. Moreover, this approach is efficient for homogeneous datasets with a dense distribution of values, significantly reducing both runtime and computational overhead compared to straightforward comparison sorting .

Adapting Counting Sort for different computing environments such as embedded systems or cloud computing introduces several complexities. In embedded systems, memory constraints mean that Counting Sort's space requirements could become problematic, requiring tuned versions with minimized memory footprint. In cloud environments, data distribution and parallelization need consideration, potentially transforming Counting Sort into a distributed algorithm like MapReduce-compatible variations, allowing it to handle vast datasets but requiring non-trivial reengineering to achieve scale efficiency without impacting its intrinsic performance characteristics .

The Counting Sort algorithm is characterized by counting the number of occurrences of each distinct element within a particular range and then using this information to determine the sorted order. It does not compare elements directly but requires additional memory proportional to the range of elements. The performance of Counting Sort is O(n + k), where n is the number of elements to sort, and k is the range of the input values. This makes it highly efficient when the range of input keys (k) is not significantly larger than the number of elements, setting it apart from comparison-based sorts like Merge Sort or Quick Sort, which have O(n log n) complexity. However, its need for extra memory can be a downside compared to in-place algorithms .

Counting Sort faces limitations in memory usage because it requires additional memory proportional to the range of input values, which can become inefficient when this range is large relative to the number of elements. It is restricted to integer sorting without inherent adaptability to other data types like floating-point numbers unless modifications such as Bucket Sort are applied. These limitations can affect its practical application, making it unsuitable for large, sparse datasets or non-integer data without further algorithmic adjustments .

Counting Sort is preferred in scenarios where the range of input values (k) is not significantly larger than the number of elements (n) to sort, making it particularly suitable for small-range integer sorting. Its advantages include linear time complexity when k is small and no conditional operations, which can improve performance on large lists of integers. However, it is limited by its requirement for additional memory to store counts and only works directly with integer-like data, not accommodating comparison-based sorting needs .

To handle large ranges of input values efficiently, Counting Sort can be adapted by techniques such as Bucket Sort. With Bucket Sort, the input range is divided into smaller ranges or buckets, allowing elements to be distributed into these buckets and sorted independently, potentially using another sorting algorithm (such as Insertion Sort) within each bucket. This method allows handling larger ranges by reducing the memory overhead and complexity associated with creating a large auxiliary array .

Counting Sort offers several advantages in high-speed data processing systems: it operates in linear time for favorable conditions, minimizes comparison overhead, and efficiently handles duplicate values. These features can contribute to significant speed gains in sorting operations within constrained memory scenarios. However, trade-offs include high additional memory requirements and limited flexibility to non-integer data types, necessitating careful consideration of input data characteristics and memory availability to harness its potential benefits optimally .

Internal sorting refers to algorithms where all data to be sorted fits entirely in the main memory, allowing constant time access to any element. This contrasts with external sorting, which handles data stored in external memory like disks, where access time is variable and directly related to data location. The choice between these affects algorithm selection significantly: internal sorting is preferred for smaller datasets, where speed is crucial, while external sorting, using methods like merge sort variations, handles large datasets beyond main memory capacity, optimizing input/output operations .

También podría gustarte