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?
[code]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;
}
}
}
}[/code]
No array de strings tente trocar a linha :
if (vetor[j] > vetor[j + 1]) {
Por:
if(vetor[j].compareTo(vetor[ j+1 ])>0)
Funcionou, mas a variável auxiliar da erro!!!
Alterei ela como String mais dá o mesmo erro ):
“Dá erro” é coisa de usuário noob, não de programador esperto. Espero que você seja um programador esperto. Qual é o erro?
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 + " ");
}
}
Tá funcionando sim. É que estou usando o NetBeans portable as vezes tem esses problemas.
[RESOLVIDO]