0

Mi problema es el siguiente:

Tengo un archivo.csv en el cual se encuentran almacenados los atributos de un objeto los cuales son: CP,Calle,numero,colonia,destinatario quiero ordenar estos atributos en base al CP con el siguiente codigo:

public class ExternalSort{

static int N = 2000000; /** size of the file in disk */
static int M = 100000;  /** max items the memory buffer can hold */

public static void externalSort(String fileName)
{
    String tfile = "temp-file-";
    int[] buffer = new int[M < N ? M : N];

    try
    {
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        int slices = (int) Math.ceil((double) N/M);

        int i, j;
        i = j = 0;
        /** Iterar a través de los elementos del archivo */
        for (i = 0; i < slices; i++)
        {
            /** Leer fragmentos de M-elementos a la vez desde el archivo */
            for (j = 0; j < (M < N ? M : N); j++)
            {
                String t = br.readLine();
                if (t != null)
                    buffer[j] = Integer.parseInt(t.substring(0,4));
                else
                    break;
            }
            /** Sort M elementos */
            Arrays.sort(buffer);

            /** Escriba los números ordenados en el archivo temporal */
            FileWriter fw = new FileWriter(tfile + Integer.toString(i) + ".txt");
            PrintWriter pw = new PrintWriter(fw);
            for (int k = 0; k < j; k++)
                pw.println(buffer[k]);

            pw.close();
            fw.close();
        }

        br.close();
        fr.close();

        /** Ahora abra cada archivo y combinelos, luego vuelva a escribirlos en el disco */
        int[] topNums = new int[slices];
        BufferedReader[] brs = new BufferedReader[slices];

        for (i = 0; i < slices; i++)
        {
            brs[i] = new BufferedReader(new FileReader(tfile + Integer.toString(i) + ".txt"));
            String t = brs[i].readLine();
            if (t != null)
                topNums[i] = Integer.parseInt(t);
            else
                topNums[i] = Integer.MAX_VALUE;
        }

        FileWriter fw = new FileWriter("external-sorted.txt");
        PrintWriter pw = new PrintWriter(fw);

        for (i = 0; i < N; i++)
        {
            int min = topNums[0];
            int minFile = 0;

            for (j = 0; j < slices; j++)
            {
                if (min > topNums[j])
                {
                    min = topNums[j];
                    minFile = j;
                }
            }

            pw.println(min);
            String t = brs[minFile].readLine();
            if (t != null)
                topNums[minFile] = Integer.parseInt(t);
                else
                topNums[minFile] = Integer.MAX_VALUE;
        }
        for (i = 0; i < slices; i++)
            brs[i].close();

        pw.close();
        fw.close();
    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch(NullPointerException ex){
        ex.printStackTrace();
    } 
}


static String generateInput(int n)
{
    String fileName = "external-sort.txt";
    Random rand = new Random();

    try
    {
        FileWriter fw = new FileWriter(fileName);
        PrintWriter pw = new PrintWriter(fw);

        for (int i = 0; i < n; i++)
            pw.println(rand.nextInt(9900) + 100);

        pw.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return fileName;
}

Se supone que me tiene que devolver el archivo ordenado en base al CP pero no lo hace.

Como ejemplo tengo los siguientes datos:

68148,Sur,45,Real Casa Blanca (Residencial),Juan Gabriel Contreras Caceres

68010,Sur,57,Elsa (Fraccionamiento),Tomas Prieto Jurado

68045,Oriente,144,Estrella (Colonia),Jorge Conde Prieto

Y el archivo ordenado tendría que resultar asi:

68010,Sur,57,Elsa (Fraccionamiento),Tomas Prieto Jurado

68045,Oriente,144,Estrella (Colonia),Jorge Conde Prieto

68148,Sur,45,Real Casa Blanca (Residencial),Juan Gabriel Contreras Caceres

2
  • Me parece que esto se a tratado con anterioridad.Mira el siguiente enlace, esta muy bien explicado y esta aceptado. enlace el 13 nov. 2016 a las 7:52
  • Gracias amigo pero el código de esa respuesta es algo complejo para mi, yo quiero pensar que mi algoritmo que hice para ordenar n numeros también funciona para ordenar String pero no encuentro exactamente como adaptarlo el 13 nov. 2016 a las 17:06

1 respuesta 1

0

si quieres ordenar una objecto de una clase creada por ti lo puedes realizar asi

implementar la Interfaz Comparable y luego implementar su metodo abstracto compareTo

import java.util.*;

public class StackOverflow implements Comparable{

private int codigo ;

public StackOverflow(int codigo)
{
    this.codigo = codigo;
}

public static void main(String[] agrs) 
{
    List<StackOverflow> lista = new ArrayList<>();
    lista.add(new StackOverflow(10));
    lista.add(new StackOverflow(3));
    lista.add(new StackOverflow(20));

    System.out.println(lista);
    Collections.sort(lista);
    System.out.println(lista);

}

public int compareTo(StackOverflow o) 
{
    //orden ascendente
    return this.codigo - o.codigo ;

    //orden descendente
    //return o.codigo - this.codigo;
}

public String toString()
{
    return ""+codigo;
}

}

Espero te sirva Saludos.

1
  • Te recomiendo que agreges un ejemplo de tu respuesta el 6 feb. 2017 a las 16:25

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.