Created
December 1, 2019 23:51
-
-
Save davidauza-engineer/539c5101ce47b0990caa1b238627f206 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Implementación algoritmo Radix Sort. | |
import java.util.Arrays; | |
class Main { | |
// Este método utiliza el algoritmo Radix Sort para ordenar un arreglo. | |
private static int[] radixSort(int[] arreglo) { | |
int max = obtenerMaximo(arreglo); | |
for(int i = 1; max / i > 0; i *= 10) { | |
arreglo = countSort(arreglo); | |
} | |
return arreglo; | |
} | |
// Este método retorna el número más grande en un arreglo de enteros. | |
private static int obtenerMaximo(int[] arreglo) { | |
int max = arreglo[0]; | |
for(int i = 1; i < arreglo.length; i++) { | |
if (arreglo[i] > max) { | |
max = arreglo[i]; | |
} | |
} | |
return max; | |
} | |
// Este método realiza el ordenamiento de un arreglo utilizando el algoritmo CountingSort. | |
private static int[] countSort(int[] arreglo) { | |
int tamanoDelArreglo = arreglo.length; | |
int[] arregloResultante = new int[tamanoDelArreglo]; | |
// Se obtiene el número mayor del arreglo. | |
int max = obtenerMaximo(arreglo); | |
// Se cuentan las ocurrencias de cada número en el arreglo original y se alamacenan en el nuevo arreglo. | |
int[] nuevoArreglo = new int[max + 1]; | |
for (int i = 0; i < tamanoDelArreglo; i++) { | |
nuevoArreglo[arreglo[i]]++; | |
} | |
// Se reemplazan los elementos del nuevoArreglo con los elementos de la suma acumulada. | |
for (int i = 1; i <= max; i++) { | |
nuevoArreglo[i] += nuevoArreglo[i - 1]; | |
} | |
// Se llena el arreglo resultante con los elementos correspondientes. | |
for (int i = tamanoDelArreglo - 1; i >= 0; i--) { | |
arregloResultante[nuevoArreglo[arreglo[i]] - 1] = arreglo[i]; | |
nuevoArreglo[arreglo[i]]--; | |
} | |
return arregloResultante; | |
} | |
// Método main que ejecuta el programa. | |
public static void main(String[] args) { | |
int[] arreglo = {90, 75, 56, 42, 3}; | |
System.out.println("Se ordenará el arreglo " + Arrays.toString(arreglo)); | |
System.out.println("El arreglo ordenado es " + Arrays.toString(radixSort(arreglo))); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment