Jump to content

Ordenar um Array de Strings


Candeias
 Share

Recommended Posts

Boa tarde,

precisso de ordenar um array com utilizando o compareTo, mas está a falta a logica penso eu..:S

Estava a pensar fazer um ciclo FOR para correr as posicoes da arrays, e dentro deste fazia outro FOR para verificar onde esta irá ficar... Confuso..lol

Exemplo:

String vetor[] = new String[20]

vector[0]="a";

vector[1]="c";

vector[2]="z";

vector[3]="d";

vector[4]="r";

vector[5]="b";

vector[6]="i";

For (0 ate 6)

  For(0 ate as posicoes ja lidas)

    Valida se a letra é maior menos ou igual... nao sei como fazer esta parte :S

Aguem pode dar uma dica??

Obrigado

Link to comment
Share on other sites

Continua a faltar a logica...

eu tenho:

for (int i=0; cont <index; i++) {
       
       if (vetor[i].compareTo(vetor[i +1 ]) < 0) { //letra i é MENOR que i+1
                System.out.println("a letra " +vetor[i].toString()+"é menor que "+ vetor[i+1]);
       } else if (vetor[i].compareTo(vetor[i + 1]) == 0) { //iguais
System.out.println("0");
       } else if (vetor[i].compareTo(vetor[i +1]) > 0) { //letra i é MAIOR que i+1
System.out.println("a letra " +vetor[i].toString()+"é maior que "+ vetor[i+1]);
       }
}

Agora em vez dos System.Out, o que devo fazer?  Falta alguma coisa no meu FOR?

Link to comment
Share on other sites

public static void main(String[] args) {   
  
        String vetor[] = new String[100];   
        vetor[0] = "z";   
        vetor[1] = "a";   
        vetor[2] = "g";   
        vetor[3] = "d";   
           
       
        for (int i = 0; i <vetor.length-1; i++) {   
               
            for (int j = 0; j <= vetor.length-1; j++) {   
               
                   
                if ((vetor[j].compareTo(vetor[j + 1]) > 0)){   
                      String temp = vetor[i];   
                      vetor[i] = vetor[j];   
                      vetor[j] = temp;   
                }   
            }   
        }   
           
           
        for (int i = 0; i < vetor.length-1; i++) {   
            System.out.println(vetor[i]);   
        }  

não estou a conseguir :S

Link to comment
Share on other sites

static <T extends Comparable<? super T>>
void selectionSort( T[] a, int n ) {
if ( a == null )
throw new NullPointerException();
if ( n > a.length )
throw new IndexOutOfBoundsException();
// while the size of the unsorted part is > 1
for ( int unsortedSize = n;
unsortedSize > 1; unsortedSize-- ) {
// find the position of the largest
// element in the unsorted section
int maxPos = 0;
for (int pos = 1; pos < unsortedSize; pos++)
if ( a[pos].compareTo(a[maxPos]) > 0 )
maxPos = pos;
// postcondition: maxPos is the position
// of the largest element in the unsorted
// part of the array
// Swap largest value with the last value
// in the unsorted part
T temp = a[unsortedSize - 1];
a[unsortedSize - 1] = a[maxPos];
a[maxPos] = temp;
}
}

Desculpa não estar identado, se fores da ESTGF (parece-me que és) vai ao slide 33 do pdf Aula06.Ordenacoes_Pesquisas_V2.pdf que tem lá este código 🙂

Cumps

@Pedro Lopes

Link to comment
Share on other sites

static <T extends Comparable<? super T>>
void selectionSort( T[] a, int n ) {
if ( a == null )
throw new NullPointerException();
if ( n > a.length )
throw new IndexOutOfBoundsException();
// while the size of the unsorted part is > 1
for ( int unsortedSize = n;
unsortedSize > 1; unsortedSize-- ) {
// find the position of the largest
// element in the unsorted section
int maxPos = 0;
for (int pos = 1; pos < unsortedSize; pos++)
if ( a[pos].compareTo(a[maxPos]) > 0 )
maxPos = pos;
// postcondition: maxPos is the position
// of the largest element in the unsorted
// part of the array
// Swap largest value with the last value
// in the unsorted part
T temp = a[unsortedSize - 1];
a[unsortedSize - 1] = a[maxPos];
a[maxPos] = temp;
}
}

Desculpa não estar identado, se fores da ESTGF (parece-me que és) vai ao slide 33 do pdf Aula06.Ordenacoes_Pesquisas_V2.pdf que tem lá este código 🙂

Cumps

ca para mim ainda é da FCUL xD tambem tive um trabalho desses mas era um pouco mais complexo, era um metodo que recebia 2 arrays ordenava o primeiro em caso de empate desempatava com o segundo e se o segundo tivesse empatado fazia-se um random e depois este metodo devolvia os indices do array ordenado..

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.