Skip to content

Instantly share code, notes, and snippets.

@emamex98
Created September 6, 2017 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emamex98/f186431e152c6b32de6a8cc7f3913737 to your computer and use it in GitHub Desktop.
Save emamex98/f186431e152c6b32de6a8cc7f3913737 to your computer and use it in GitHub Desktop.
Radix Sort que soporta números negativos
public class RadixSortB {
public void radixSort(int[] numbers){
int i, nNeg = 0, length = numbers.length, j = 0, k = 0, max, min, tmp;
// Busca cuantos numeros son negativos en el arreglo
for(i=0; i<length; i++) {
if(numbers[i] < 0)
nNeg++;
}
// Si existen numeros negativos, crea un arreglo de negativos y otro de de positivos
if(nNeg != 0) {
int[] posNumbers = new int[(length - nNeg)];
int[] negNumbers = new int[nNeg];
for(i=0; i<length; i++) {
if(numbers[i] < 0) {
negNumbers[j] = numbers[i];
j++;
}
else {
posNumbers[k] = numbers[i];
k++;
}
}
// Busca valores maximo y minimo
min = negNumbers[0];
max = posNumbers[0];
// Convierte los valores negativos a positivos (temporalmente)
negNumbers[0] *= -1;
for (i=1; i < negNumbers.length; i++) {
negNumbers[i] *= -1;
if(negNumbers[i] > min)
min = negNumbers[i];
}
for (i=1; i < posNumbers.length; i++) {
if(posNumbers[i] > max)
max = posNumbers[i];
}
// Llama metodo sort (ultimo parametro es true si se quiere orden ascendiente y false desciente)
sort(negNumbers,min, false);
sort(posNumbers,max, true);
// Convierte los valores de los numeros negativos ordenados desciendietemente a negativos
for(i=0; i<negNumbers.length; i++)
negNumbers[i] *= -1;
for(i=0; i<negNumbers.length; i++)
System.out.print(negNumbers[i] + ", ");
for(i=0; i<posNumbers.length; i++)
System.out.print(posNumbers[i] + ", ");
System.out.println("");
}
}
private int[] sort(int[] a, int m, boolean ascending){
int i, n=a.length, exp = 1;
int[] b = new int[10];
if(ascending==true){
while (m / exp > 0) {
int[] bucket = new int[10];
for (i = 0; i < n; i++)
bucket[(a[i] / exp) % 10]++;
for (i = 1; i < 10; i++)
bucket[i] += bucket[i - 1];
for (i = n - 1; i >= 0; i--)
b[--bucket[(a[i] / exp) % 10]] = a[i];
for (i = 0; i < n; i++)
a[i] = b[i];
exp *= 10;
}
}
else {
// Este es el mismo algoritmo pero para ordenar en orden desciente
while (m/exp>0) {
int[] bucket = new int[10];
for (i = 0; i < n; i++)
bucket[9-a[i]/exp%10]++;
for (i = 1; i < 10; i++)
bucket[i]+=bucket[i-1];
for (i = n-1; i >= 0; i--)
b[--bucket[9-a[i]/exp%10]]=a[i];
for (i = 0; i < n; i++){
a[i]=b[i];
}
exp*=10;
}
}
return a;
}
public static void main(String[] args) {
int[] nums = {2,56,-32,49,-32,-105,-45,-27,101};
RadixSortB r = new RadixSortB();
r.radixSort(nums);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment