[RESOLVIDO] Ordenar Strings com BubbleSort

5 respostas
Luccas_Ferreira

Para ter um método bubbleSort que ordene Strings como seria?

No código abaixo é para ordenar números!
Como eu faria isso com String?

public class Ordenacao {

    private int[] vetor;

    public int[] getVetor() {
        return vetor;
    }

    public void setVetor(int[] vetor) {
        this.vetor = vetor;
    }

    public void bubbleSort() {
        int tamanho = vetor.length;

        for (int i = 0; i < tamanho - 1; i++) {
            for (int j = 0; j < tamanho - 1 - i; j++) {
                if (vetor[j] > vetor[j + 1]) {
                    int auxiliar = vetor[j];
                    vetor[j] = vetor[j + 1];
                    vetor[j + 1] = auxiliar;
                }
            }
        }
    }

5 Respostas

paulohms

No array de strings tente trocar a linha :

if (vetor[j] > vetor[j + 1]) {

Por:

if(vetor[j].compareTo(vetor[ j+1 ])>0)
Luccas_Ferreira

Funcionou, mas a variável auxiliar da erro!!!
Alterei ela como String mais dá o mesmo erro ):

E

“Dá erro” é coisa de usuário noob, não de programador esperto. Espero que você seja um programador esperto. Qual é o erro?

DavidUser

if(vetor[j].compareTo(vetor[ j+1 ])>0) {

olha ele aí {

verifica se não esqueceu o abre chaves, pois este código funciona perfeitamente:

class Ordenacao {

	private String[] vetor;

	public String[] getVetor() {
		return vetor;
	}

	public void setVetor(String[] vetor) {
		this.vetor = vetor;
	}

	public void bubbleSort() {
		int tamanho = vetor.length;

		for (int i = 0; i < tamanho - 1; i++) {
			for (int j = 0; j < tamanho - 1 - i; j++) {
				if(vetor[j].compareTo(vetor[ j+1 ])>0) { 
					String auxiliar = vetor[j];
					vetor[j] = vetor[j + 1];
					vetor[j + 1] = auxiliar;
				}
			}
		}
	}
}

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String []vector = {"2", "1", "5", "4", "3"};
		Ordenacao o = new Ordenacao();
		o.setVetor(vector);
		o.bubbleSort();
		vector = o.getVetor();
		
		for (String i : vector)
			System.out.print(i + " ");
	}

}
Luccas_Ferreira

Tá funcionando sim. É que estou usando o NetBeans portable as vezes tem esses problemas.

[RESOLVIDO]

Criado 26 de fevereiro de 2013
Ultima resposta 26 de fev. de 2013
Respostas 5
Participantes 4