Está en la página 1de 3

"Ordenamiento por Método de Distribución" utilizando cubetas o "buckets".

1. Se define una clase Buckets que contiene métodos estáticos para ordenar números utilizando el algoritmo de
ordenamiento por distribución. Contiene las constantes:
NUM_RANGOS representa la cantidad de cubetas o "buckets" a utilizar.
RANGO es el tamaño de cada rango o cubeta.
RANGO_MAXIMO es el valor máximo posible para los datos generados aleatoriamente.
2. En el método main, se generan aleatoriamente 50 números mediante el método generarDatosAleatorios. Estos
datos representarán los elementos a ordenar.

3. El método ordenamientoPorDistribucion distribuye los números generados en las cubetas. Para ello:
• Se crea una lista de listas de enteros (buckets) que representan las cubetas.
• Se inicializan las "cubetas" utilizando un ciclo for, creando un total de NUM_RANGOS (en este caso, 10)
"cubetas" vacías.
• Los números se distribuyen en las cubetas calculando el índice del cubo al que pertenecen basado en su
valor y en el tamaño de cada rango.
Donde para cada número (dato), se calcula el índice del "bucket" al que pertenece mediante la fórmula: int
bucketIndex = (dato - 1) / RANGO;
dato representa el valor del número actual del arreglo.
RANGO es el tamaño de cada rango o cubeta (en este caso, 10).
(dato - 1) / RANGO calcula el índice del "bucket" basado en el valor del número y el tamaño del rango.
Restar 1 al número se hace para asegurar que los valores del rango estén entre 1 y 100, ya que los rangos
se definen de 1 a 10, 11 a 20, y así sucesivamente.
• Una vez calculado el índice de la "cubeta" correspondiente, se agrega el número a esa "cubeta" usando
buckets.get(bucketIndex).add(dato).

4. Se imprime el contenido de cada "bucket" antes de ordenarlos, utilizando el método imprimirBuckets.

5. Luego, se ordenan los elementos de cada "bucket" por separado utilizando Collections.sort(bucket).

6. El método ordenarYMostrarDatos une los datos ordenados de cada "bucket" en una lista única y luego los
imprime.

7. El método generarDatosAleatorios genera un arreglo de tamaño dado con números aleatorios entre 1 y
RANGO_MAXIMO.

8. Los métodos imprimirArreglo e imprimirBuckets son métodos auxiliares para imprimir los arreglos y el contenido
de los "buckets" respectivamente. Donde es necesario que cada lista de elementos enteros sea convertida en un
arreglo de enteros. Esto es útil para imprimir los números contenidos en una "cubeta" específica en forma de
arreglo. Por ejemplo: buckets.get(i).stream().mapToInt(Integer::intValue).toArray() toma la lista de enteros en la
posición i de la lista buckets, la convierte en un flujo de enteros, convierte cada elemento en su valor entero y
finalmente lo convierte de nuevo en un arreglo de enteros.
Código
package valenzuela;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Bucket {


private static final int NUM_RANGOS = 10;
private static final int RANGO = 10; // Tamaño de cada rango
private static final int RANGO_MAXIMO = 100; // Valor máximo

public static void main(String[] args) {


int[] datos = generarDatosAleatorios(50);
System.out.println("Datos originales:");
imprimirArreglo(datos);

List<List<Integer>> buckets = ordenamientoPorDistribucion(datos);

System.out.println("Datos ordenados:");
ordenarYMostrarDatos(buckets);
}

public static List<List<Integer>> ordenamientoPorDistribucion(int[] datos) {


List<List<Integer>> buckets = new ArrayList<>(NUM_RANGOS);

// Inicializar buckets
for (int i = 0; i < NUM_RANGOS; i++) {
buckets.add(new ArrayList<>());
}

// Distribuir elementos en buckets


for (int dato : datos) {
int bucketIndex = (dato - 1) / RANGO; // Calcular el índice del bucket/rango
buckets.get(bucketIndex).add(dato);
}

System.out.println("Contenido de los buckets antes de ordenar y unir:");


imprimirBuckets(buckets);

// Ordenar cada bucket por separado


for (List<Integer> bucket : buckets) {
Collections.sort(bucket);
}

return buckets;
}

public static void ordenarYMostrarDatos(List<List<Integer>> buckets) {


List<Integer> datosOrdenados = new ArrayList<>();

// Reunir elementos de los buckets en una sola lista


for (List<Integer> bucket : buckets) {
datosOrdenados.addAll(bucket);
}

imprimirArreglo(datosOrdenados.stream().mapToInt(Integer::intValue).toArray());
}
public static int[] generarDatosAleatorios(int cantidad) {
int[] datos = new int[cantidad];
for (int i = 0; i < cantidad; i++) {
datos[i] = (int) (Math.random() * RANGO_MAXIMO) + 1;
}
return datos;
}

public static void imprimirArreglo(int[] arreglo) {


for (int num : arreglo) {
System.out.print(num + " ");
}
System.out.println();
}

public static void imprimirBuckets(List<List<Integer>> buckets) {


for (int i = 0; i < buckets.size(); i++) {
System.out.print("Bucket " + (i + 1) + ": ");

imprimirArreglo(buckets.get(i).stream().mapToInt(Integer::intValue).toArray());
}
}
}

Ejecución
Datos originales:
44 57 5 98 20 70 35 85 32 98 49 40 61 25 10 100 20 54 68 85 23 27 18 29 98 57 92 28 70 38 1 51 2 4
2 67 90 87 91 28 70 7 71 45 7 40 88 26 39 42
Contenido de los buckets antes de ordenar y unir:
Bucket 1: 5 10 1 2 4 2 7 7
Bucket 2: 20 20 18
Bucket 3: 25 23 27 29 28 28 26
Bucket 4: 35 32 40 38 40 39
Bucket 5: 44 49 45 42
Bucket 6: 57 54 57 51
Bucket 7: 70 61 68 70 67 70
Bucket 8: 71
Bucket 9: 85 85 90 87 88
Bucket 10: 98 98 100 98 92 91
Datos ordenados:
1 2 2 4 5 7 7 10 18 20 20 23 25 26 27 28 28 29 32 35 38 39 40 40 42 44 45 49 51 54 57 57 61 67 68
70 70 70 71 85 85 87 88 90 91 92 98 98 98 100

También podría gustarte