How to sort and sort strings without using Collection?

Asked

Viewed 2,969 times

2

I am creating a register of employees with some fields(name, email, phone and salary) in ArrayList which are recorded in txt.

After the data is entered into the array (before passing to txt) they need to be sorted by name, which is the first field from left to right.

And this is where the problem is, because I can’t use any ready method of sorting type Sort. I have to create a quicksort.

I’ve tried a lot of ways, and I couldn’t. I thought to try with the string compare, but I don’t know how he could do to sort alphabetically.

Will it work? Can someone give me a light?

Main class:

public static void main(String[] args) throws IOException 
{
ArrayList<Funcionario> funcionarios = new ArrayList<Funcionario>(); 



... menu do programa..

case 1:   
   Funcionario func = new Funcionario();
   func.cadastrar(); 
   funcionarios.add(func);
   System.in.read(); 
   System.out.println("\n\nFuncionario cadastrado: " + func.toString());                  
break;

Register class

public void cadastrar()
{
     System.out.println("\n\n\n\n\n\n\n\n\n----- Cadastro de funcionário -----");

     System.out.print("\nInforme o nome: ");
     String nome = ler.nextLine();
     this.setNome(nome);

     System.out.print("\nInforme o e-mail: ");
     String email = ler.nextLine();
     this.setEmail(email);

     boolean valida;
     do
     {
        System.out.print("\nInforme o telefone: ");
        String telefone = ler.nextLine();

       if(telefone.length() != 10)
        {
           System.out.println("Erro!!\nO formato exige 10 dígitos\n");
           valida = false;
        }
        else 
        {
           valida = true;
           this.setTelefone(telefone);
        }
     }while(!valida);

     do
     {
        System.out.print("\nInforme o salário: R$ ");
        float salario = ler.nextFloat();
        if(salario <= 0)
        {
           System.out.println("ERRO!! Valor inválido");
           valida = false;
        }
        else 
        {
           valida = true;
           this.setSalario(salario);
        }
     }while(!valida);
 PrintWriter gravarTxt = new PrintWriter(arquivo);
 gravarTxt.printf("\r\n"+this.nome+" "+this.email+" "+this.telefone+" R$ "+this.salario);
 gravarTxt.flush();
}
  • 3

    Hi Maximilian, all right? It’s easier to help you if you create one mvce demonstrating exactly where your problem is. The method compare is useful for comparing lexicographic order yes (it can replace the part that would be made with comparison operators >, < in the case of types such as int).

  • Thanks for the touch, Anthony. Fixed

  • 1

    Check this out, see if you can understand and apply your http://stackoverflow.com/questions/31377448/how-to-sorting-in-array-list-without-using-collections-in-javacode

2 answers

2


Try the following:

for (int i = 0; i < lista.size(); i++) {

    for (int j = lista.size() - 1; j > i; j--) {
        if (lista.get(i).getNome().compareToIgnoreCase(lista.get(j).getNome()) > 0) {

            Pessoa tmp = lista.get(i);
            lista.set(i, lista.get(j));
            lista.set(j, tmp);

        }
    }
}

In this code I used two loops, where the first one goes through the indices of the array in an increasing way, and the second one in a decreasing form until the point where the first one is.

The method compareToIgnoreCase ignores the "case" of words and compares the word of the current Dice with later indices. Whenever the result is greater than 0, it means that the string on the right is before the string on the left (our current index), and this causes you to swap the two positions in the array.

This is an implementation of Bubble Sort.

See working on IDEONE

Reference: How to do Sorting in array list without using Collections in Java

  • It worked, brother. Thank you so much

1

Use the method Collections.sort(List<T> list, Comparator<? super T> c).

For this you need to create a class that implements the interface Comparable<T>.

Whereas you have a list of employees and this class has the following attributes and methods:

public class Funcionario {

    private final String nome;

    public Funcionario(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }
}

In implementing Comparable, you must override the method compare. As you want to sort by name attribute, your comparator can look like this:

import java.util.Comparator;

public class FuncionarioComparator implements Comparator<Funcionario> { 

    @Override
    public int compare(Funcionario funcionario1, Funcionario funcionario2) {
        return funcionario1.getNome().compareTo(funcionario2.getNome());
    } 
}

Having this comparator, you can use it in the method sort:

ArrayList<Funcionario> funcionarios = new ArrayList<>();
// Populando 'funcionarios'...

Collections.sort(funcionarios, new FuncionarioComparator());

Online example.

  • 2

    It can not use any ready method of ordering, have to do manually, see the question.

  • 1

    Unfortunately we can not use the Sort, Renan, Thanks for the dedication in creating the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.