How to sort and sort strings without using Collection?

2

I am creating an employee record with some fields (name, email, phone and salary) in ArrayList that are written to txt.

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

And here's the problem, because I can not use any sort order sort method. I have to create a quicksort.

I have tried in many ways and I have not been able to. I thought about trying with the string compare, but I do not know how it 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;

Class registration

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();
}
    
asked by anonymous 15.11.2015 / 19:22

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 runs through the indexes of the array incrementally, and the second decreases to the point where the first one is.

The method compareToIgnoreCase ignores the "case" of the words and compares the word of the current index with later indices. Whenever the result is greater than 0, it means that the right string is preceding the string to the left (our current index), and that makes it change the two of position in the array.

This is an implementation of bubble sort .

See working at IDEONE

Reference: How to do sorting in array without using collections in Java

    
15.11.2015 / 22:33
1

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

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

Considering that 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;
    }
}

When you implement Comparable , you must overwrite the compare method. As you want to sort by the name attribute, your comparator might 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 comparer, you can use it in the sort method:

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

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

Example online.

    
15.11.2015 / 22:10