Ordem alfabética

Tenho vamos supoer uma classe de revistas, em um array será então dada as informações como nome da revista por exemplo. Porem gostaria de por em ordem elas e vi em algum lugar sobre ordenar arrays em ordem alfabética através disto: Arrays.sort(String[] vect) porém nao intendi muito bem alguem pode me esclarecer esta duvida?

na verdade a classe tem um método
public static void sort(Object[] a)

como String é subclasse de object, ela pode ser “sorteada” pela classe

o que essa classe faz?
ela ordena o vetor com base:

  • com o hashCode() do objeto, que é um código que identifica o objeto
  • com base no método compareTo() do objeto
  • ???

Desculpa mais realmente sou um pouco leigo no assunto … é um Array vamos supor de varios titulos, esses titulos apresentam na Classe Livros, esses titulos eu pretendia pegar eles e por em ordem alfabética…vamos supor declarei assim private Livros[] lista_de_livros = new Livros[1000];
então nas lista_de_livros eu xamaria o getTitulo porém preciso ordenar alfabéticamente … pode ajudar? :slight_smile:

Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort.

Ex:

[code]import java.util.*;

public class teste {
public static void main(String[] args) {
String a[] = {"Maria", "Joao", "Renan"};
ArrayList lista = new ArrayList();
for(int i = 0; i < a.length; i++) {
lista.add(a[i]);
}

    Collections.sort&#40;lista&#41;;
    
    System.out.println&#40;lista&#41;;        
&#125;    

}[/code]

A saida vai estar ordenada…

Te ajudou…?

[quote=“renan_daniel”]Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort.

Ex:

[code]import java.util.*;

public class teste {
public static void main(String[] args) {
String a[] = {"Maria", "Joao", "Renan"};
ArrayList lista = new ArrayList();
for(int i = 0; i < a.length; i++) {
lista.add(a[i]);
}

    Collections.sort&#40;lista&#41;;
    
    System.out.println&#40;lista&#41;;        
&#125;    

}[/code]

A saida vai estar ordenada…

Te ajudou…?[/quote]

Na verdade, a maneira que faço (e acho ideal) é escrever o algoritmo de sort, tipo (usei esse codigo, entao funciona):

public String &#91;&#93; sort&#40;String &#91;&#93; strArray&#41; throws Exception &#123;
    int j;
    int limit = strArray.length;
    int    st = -1;
    while&#40;st &lt; limit&#41; &#123;
        st++;
        limit--;
        boolean swapped = false;
        for&#40;j = st; j &lt; limit; j++&#41; &#123;
            int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;;
            if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                strArrayAt = strArrayAt - 32;
            &#125;
            int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;;
            if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                strArrayAtPlusOne = strArrayAtPlusOne - 32;
            &#125;
            if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                String tempValue = strArray&#91;j&#93;;
                strArray&#91;j&#93;      = strArray&#91;j + 1&#93;;
                strArray&#91;j + 1&#93;  = tempValue;
                swapped = true;
            &#125;
        &#125;
        for&#40;j = limit; --j &gt;= st;&#41; &#123;
            int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;;
            if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                strArrayAt = strArrayAt - 32;
            &#125;
            int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;;
            if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                strArrayAtPlusOne = strArrayAtPlusOne - 32;
            &#125;
            if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                String tempValue = strArray&#91;j&#93;;
                strArray&#91;j&#93;      = strArray&#91;j + 1&#93;;
                strArray&#91;j + 1&#93;  = tempValue;
                swapped = true;
            &#125;
        &#125;
    &#125;
    return strArray;
&#125;

Poderia me explicar sobre os valores que apresentou neste seu Sort?

“if(strArrayAt >= 97 && strArrayAt <= 122)”

por exemplo esta linha realmente nao intendi como o metodo funciona =/. Obrigado!

Olá, renam, não precisa fazer o for para preencher a List com os objetos do array. Basta fazer assim:

[code]import java.util.*;

public class teste {
public static void main(String[] args) {
String a[] = {"Maria", "Joao", "Renan"};

	List lista = Arrays.asList&#40;a&#41;;

	Collections.sort&#40;lista&#41;;

	System.out.println&#40;lista&#41;;
&#125;

}[/code]

[quote=“omegatiger”]Poderia me explicar sobre os valores que apresentou neste seu Sort?

“if(strArrayAt >= 97 && strArrayAt <= 122)” [/quote]
Creio que esse if deve estar relacionado ao codigo ascii dos caracteres. Bom, melhor do que fazer a ordenação dessa maneira, seria criar um Comparator.

valeuz…

[quote=“omegatiger”]Poderia me explicar sobre os valores que apresentou neste seu Sort?

“if(strArrayAt >= 97 && strArrayAt <= 122)”

por exemplo esta linha realmente nao intendi como o metodo funciona =/. Obrigado![/quote]

Isso significa de A até Z em minusculo, em ASCII!

É uma versão bi-direcional do algoritmo da bolha.

Tem espaço pra melhorias aí (por exemplo, um ‘ç’ não seria considerado como ‘c’, e não seria ordenado direito (viria depois do z, por que o ASCII de ‘ç’ é maior que o ascii de ‘z’).

abs

[quote=“jack_-_ganzha”]Olá, renam, não precisa fazer o for para preencher a List com os objetos do array. Basta fazer assim:

[code]import java.util.*;

public class teste {
public static void main(String[] args) {
String a[] = {"Maria", "Joao", "Renan"};

	List lista = Arrays.asList&#40;a&#41;;

	Collections.sort&#40;lista&#41;;

	System.out.println&#40;lista&#41;;
&#125;

}[/code]

Essa eu naum conhecia, valeu…

[quote=“mavi”][quote=“renan_daniel”]Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort.

Ex:

[code]import java.util.*;

public class teste {
public static void main(String[] args) {
String a[] = {"Maria", "Joao", "Renan"};
ArrayList lista = new ArrayList();
for(int i = 0; i < a.length; i++) {
lista.add(a[i]);
}

    Collections.sort&#40;lista&#41;;
    
    System.out.println&#40;lista&#41;;        
&#125;    

}[/code]

A saida vai estar ordenada…

Te ajudou…?[/quote]

Na verdade, a maneira que faço (e acho ideal) é escrever o algoritmo de sort, tipo (usei esse codigo, entao funciona):

public String &#91;&#93; sort&#40;String &#91;&#93; strArray&#41; throws Exception &#123; int j; int limit = strArray.length; int st = -1; while&#40;st &lt; limit&#41; &#123; st++; limit--; boolean swapped = false; for&#40;j = st; j &lt; limit; j++&#41; &#123; int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;; if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123; strArrayAt = strArrayAt - 32; &#125; int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;; if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123; strArrayAtPlusOne = strArrayAtPlusOne - 32; &#125; if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123; String tempValue = strArray&#91;j&#93;; strArray&#91;j&#93; = strArray&#91;j + 1&#93;; strArray&#91;j + 1&#93; = tempValue; swapped = true; &#125; &#125; for&#40;j = limit; --j &gt;= st;&#41; &#123; int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;; if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123; strArrayAt = strArrayAt - 32; &#125; int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;; if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123; strArrayAtPlusOne = strArrayAtPlusOne - 32; &#125; if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123; String tempValue = strArray&#91;j&#93;; strArray&#91;j&#93; = strArray&#91;j + 1&#93;; strArray&#91;j + 1&#93; = tempValue; swapped = true; &#125; &#125; &#125; return strArray; &#125; [/quote]

pra comparar Strings n eh mais facil fazer isso:

if &#40;str1.compareTo&#40;str2&#41; &gt; 0&#41;&#123;
 // a str1 vem depois de str2
&#125;
else&#123;
 // a str1 vem antes &#40;ou junto, caso o valor seja 0&#41; da str2
&#125;

alem de q no seu codigo vc esta comparando soh a primeira, pelo seu codigo essas duas strings seriam iguas:

e tipo, eu prefiro usar o quicksort:

public void troca&#40;String array&#91;&#93;, int i, int j&#41;&#123;
 String aux = array&#91;i&#93;;
 array&#91;i&#93; = array&#91;j&#93;;
 array&#91;j&#93; = aux;
&#125;
public void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#41;&#123;
  int x = particao&#40;p, q, array&#41;;
  quicksort&#40;p, x - 1, array&#41;;
  quicksort&#40;x + 1, q, array&#41;;
 &#125;
&#125;
public int particao&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 int j = p - 1;
 String aux = array&#91;q&#93;;
 for &#40;int i = p; i &lt;= q; i++&#41;&#123;
  if &#40;array&#91;i&#93;.compareTo&#40;aux&#41; &lt;= 0&#41; troca&#40;array, i, ++j&#41;;
 &#125;
 return j;
&#125;

dai pra iniciar o quicksort chame:

quicksort&#40;0, array.length - 1, array&#41;;

public void ordenar() {
Livros temp = new Livros();
temp = (Livros) lista_de_livros[i];
String a[] ={temp.getTitulo()};
List lista = Arrays.asList(a);
Collections.sort(lista);
System.out.println(lista);
}

  //Preciso no Array a[] o Titulo dos livros que ja tem em um array. Ae não sei se devo percorrer o Array largando as variaveis realmente estou em duvidas sendo que vamos supor é um Array de lista_de_livros onde apresenta Titulos, Ano, Preco ... porem preciso apenas o titulo, será através dele a ordenagem ... porém nao consigo efetuar a operação...

[quote=“Felipe”][quote=“mavi”][quote=“renan_daniel”]Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort.

Ex:

[code]import java.util.*;

public class teste {
public static void main(String[] args) {
String a[] = {"Maria", "Joao", "Renan"};
ArrayList lista = new ArrayList();
for(int i = 0; i < a.length; i++) {
lista.add(a[i]);
}

    Collections.sort&#40;lista&#41;;
    
    System.out.println&#40;lista&#41;;        
&#125;    

}[/code]

A saida vai estar ordenada…

Te ajudou…?[/quote]

Na verdade, a maneira que faço (e acho ideal) é escrever o algoritmo de sort, tipo (usei esse codigo, entao funciona):

public String &#91;&#93; sort&#40;String &#91;&#93; strArray&#41; throws Exception &#123; int j; int limit = strArray.length; int st = -1; while&#40;st &lt; limit&#41; &#123; st++; limit--; boolean swapped = false; for&#40;j = st; j &lt; limit; j++&#41; &#123; int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;; if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123; strArrayAt = strArrayAt - 32; &#125; int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;; if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123; strArrayAtPlusOne = strArrayAtPlusOne - 32; &#125; if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123; String tempValue = strArray&#91;j&#93;; strArray&#91;j&#93; = strArray&#91;j + 1&#93;; strArray&#91;j + 1&#93; = tempValue; swapped = true; &#125; &#125; for&#40;j = limit; --j &gt;= st;&#41; &#123; int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;; if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123; strArrayAt = strArrayAt - 32; &#125; int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;; if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123; strArrayAtPlusOne = strArrayAtPlusOne - 32; &#125; if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123; String tempValue = strArray&#91;j&#93;; strArray&#91;j&#93; = strArray&#91;j + 1&#93;; strArray&#91;j + 1&#93; = tempValue; swapped = true; &#125; &#125; &#125; return strArray; &#125; [/quote]

pra comparar Strings n eh mais facil fazer isso:

if &#40;str1.compareTo&#40;str2&#41; &gt; 0&#41;&#123;
 // a str1 vem depois de str2
&#125;
else&#123;
 // a str1 vem antes &#40;ou junto, caso o valor seja 0&#41; da str2
&#125;

alem de q no seu codigo vc esta comparando soh a primeira, pelo seu codigo essas duas strings seriam iguas:

e tipo, eu prefiro usar o quicksort:

public void troca&#40;String array&#91;&#93;, int i, int j&#41;&#123;
 String aux = array&#91;i&#93;;
 array&#91;i&#93; = array&#91;j&#93;;
 array&#91;j&#93; = aux;
&#125;
public void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#41;&#123;
  int x = particao&#40;p, q, array&#41;;
  quicksort&#40;p, x - 1, array&#41;;
  quicksort&#40;x + 1, q, array&#41;;
 &#125;
&#125;
public int particao&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 int j = p - 1;
 String aux = array&#91;q&#93;;
 for &#40;int i = p; i &lt;= q; i++&#41;&#123;
  if &#40;array&#91;i&#93;.compareTo&#40;aux&#41; &lt;= 0&#41; troca&#40;array, i, ++j&#41;;
 &#125;
 return j;
&#125;

dai pra iniciar o quicksort chame:

quicksort&#40;0, array.length - 1, array&#41;; [/quote]

Nunca usei o quicksort, mas em termos de performance ele parece absurdamente horrivel (vide fato de ficar passando o array pra lá e pra cá…parece totalmente não escalável).

Enfim, como disse anteriormente, whatever floats your boat.

O que propus é muito mais rápido, e pouco eficaz (dependendo da aplicação)…mas no caso da minha aplicação (o chatserver da america online), me foi muito útil para ordenar os nomes dos usuários no drop down de usuários.

pelo contrario!!! o quicksort eh um dos metodos de ordenacao mais rapidos!!! isso pra n dizer o mais rapido…

qnto a passar os arrays, lembre-se de q os arrays sao passados por referencia, ou seja, eles vao passar apenas a posicao q o array ocupa na memoria, como se fosse passar um simpes int!!! eh por isso q se vc passar um array por um metodo, se vc alterar ele as alteracoes seram validas para o “original”

e tb, eu tava passando o array como argumento apenas pra mostrar como funciona, se o array estiver em uma variavel global vc n precisa ficar passando ele…

[quote=“Felipe”]pelo contrario!!! o quicksort eh um dos metodos de ordenacao mais rapidos!!! isso pra n dizer o mais rapido…

qnto a passar os arrays, lembre-se de q os arrays sao passados por referencia, ou seja, eles vao passar apenas a posicao q o array ocupa na memoria, como se fosse passar um simpes int!!! eh por isso q se vc passar um array por um metodo, se vc alterar ele as alteracoes seram validas para o “original”

e tb, eu tava passando o array como argumento apenas pra mostrar como funciona, se o array estiver em uma variavel global vc n precisa ficar passando ele…[/quote]

Nah…
Eu escolhi o mais rápido que encontrei quando fiz a aplicação…e por via das dúvidas resolvi testar os códigos:

Resultado foi:

Bubble-&gt;Amostragem 0&#58; 210ms
Bubble-&gt;Amostragem 1&#58; 200ms
Bubble-&gt;Amostragem 2&#58; 201ms
Bubble-&gt;Amostragem 3&#58; 190ms
Bubble-&gt;Amostragem 4&#58; 210ms
Bubble-&gt;Average&#58; 202ms
Bubble-&gt;Output&#58; 1,2,3,4,5,6,7,8,9,
Quicksort-&gt;Amostragem 0&#58; 381ms
Quicksort-&gt;Amostragem 1&#58; 380ms
Quicksort-&gt;Amostragem 2&#58; 411ms
Quicksort-&gt;Amostragem 3&#58; 370ms
Quicksort-&gt;Amostragem 4&#58; 381ms
Quicksort-&gt;Average&#58; 384ms
Quicksort-&gt;Output&#58; 1,2,3,4,5,6,7,8,9,

O código que usei pra chegar a isso foi:

public class Bench &#123;
    public static void main&#40;String &#91;&#93; argvs&#41; throws Exception &#123;
        String &#91;&#93; abc = new String&#91;&#93; &#123;&quot;9&quot;, &quot;3&quot;, &quot;1&quot;, &quot;2&quot;, &quot;4&quot;, &quot;8&quot;, &quot;6&quot;, &quot;7&quot;, &quot;5&quot;&#125;;
        Bench   bench = new Bench&#40;&#41;;
        int       len = abc.length;
        int     total = 0;
        int iteration = 5;
        // bubble
        for&#40;int x = 0; x &lt; iteration; x++&#41; &#123;
            long str = System.currentTimeMillis&#40;&#41;;
            for&#40;int y = 0; y &lt; 100000; y++&#41; &#123;
                bench.bubble&#40;abc&#41;;
            &#125;
            long end = System.currentTimeMillis&#40;&#41;;
            total   += end - str;
            System.out.println&#40;&quot;Bubble-&gt;Amostragem &quot; + x + &quot;&#58; &quot; + &#40;end - str&#41; + &quot;ms&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;Bubble-&gt;Average&#58; &quot; + Math.round&#40;total / iteration&#41; + &quot;ms&quot;&#41;;
        System.out.print&#40;&quot;Bubble-&gt;Output&#58; &quot;&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + &quot;,&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;&quot;&#41;;
        // quicksort
        total = 0;
        for&#40;int x = 0; x &lt; iteration; x++&#41; &#123;
            long str = System.currentTimeMillis&#40;&#41;;
            for&#40;int y = 0; y &lt; 100000; y++&#41; &#123;
                bench.quicksort&#40;0, len - 1, abc&#41;;
            &#125;
            long end = System.currentTimeMillis&#40;&#41;;
            total   += end - str;
            System.out.println&#40;&quot;Quicksort-&gt;Amostragem &quot; + x + &quot;&#58; &quot; + &#40;end - str&#41; + &quot;ms&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;Quicksort-&gt;Average&#58; &quot; + Math.round&#40;total / iteration&#41; + &quot;ms&quot;&#41;;
        System.out.print&#40;&quot;Quicksort-&gt;Output&#58; &quot;&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + &quot;,&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;&quot;&#41;;
    &#125;
    void troca&#40;String array&#91;&#93;, int i, int j&#41; &#123;
        String aux = array&#91;i&#93;; 
        array&#91;i&#93;   = array&#91;j&#93;; 
        array&#91;j&#93;   = aux; 
    &#125; 
    void quicksort&#40;int p, int q, String array&#91;&#93;&#41; &#123; 
        if &#40;p &lt; q&#41; &#123;
            int x = particao&#40;p, q, array&#41;; 
            quicksort&#40;p, x - 1, array&#41;; 
            quicksort&#40;x + 1, q, array&#41;; 
        &#125; 
    &#125; 
    int particao&#40;int p, int q, String array&#91;&#93;&#41;&#123; 
        int j = p - 1; 
        String aux = array&#91;q&#93;; 
        for &#40;int i = p; i &lt;= q; i++&#41;&#123; 
            if &#40;array&#91;i&#93;.compareTo&#40;aux&#41; &lt;= 0&#41; troca&#40;array, i, ++j&#41;; 
        &#125; 
        return j; 
    &#125;
    String &#91;&#93; bubble&#40;String &#91;&#93; strArray&#41; throws Exception &#123;
        int j;
        int limit = strArray.length;
        int    st = -1;
        while&#40;st &lt; limit&#41; &#123;
            st++;
            limit--;
            boolean swapped = false;
            for&#40;j = st; j &lt; limit; j++&#41; &#123;
                int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                    strArrayAt = strArrayAt - 32;
                &#125;
                int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                    strArrayAtPlusOne = strArrayAtPlusOne - 32;
                &#125;
                if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                    String tempValue = strArray&#91;j&#93;;
                    strArray&#91;j&#93;      = strArray&#91;j + 1&#93;;
                    strArray&#91;j + 1&#93;  = tempValue;
                    swapped = true;
                &#125;
            &#125;
            for&#40;j = limit; --j &gt;= st;&#41; &#123;
                int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                    strArrayAt = strArrayAt - 32;
                &#125;
                int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                    strArrayAtPlusOne = strArrayAtPlusOne - 32;
                &#125;
                if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                    String tempValue = strArray&#91;j&#93;;
                    strArray&#91;j&#93;      = strArray&#91;j + 1&#93;;
                    strArray&#91;j + 1&#93;  = tempValue;
                    swapped = true;
                &#125;
            &#125;
        &#125;
        return strArray;
    &#125;
&#125;

Por um segundo pensei que eu estivesse errado sobre a velocidade…mas estava certo :slight_smile:
Vivendo e aprendendo :wink:

EDIT: Tinha esquecido de zerar o “total” e por isso nao estava correto o resultado.

[quote=“mavi”][quote=“Felipe”]pelo contrario!!! o quicksort eh um dos metodos de ordenacao mais rapidos!!! isso pra n dizer o mais rapido…

qnto a passar os arrays, lembre-se de q os arrays sao passados por referencia, ou seja, eles vao passar apenas a posicao q o array ocupa na memoria, como se fosse passar um simpes int!!! eh por isso q se vc passar um array por um metodo, se vc alterar ele as alteracoes seram validas para o “original”

e tb, eu tava passando o array como argumento apenas pra mostrar como funciona, se o array estiver em uma variavel global vc n precisa ficar passando ele…[/quote]

Nah…
Eu escolhi o mais rápido que encontrei quando fiz a aplicação…e por via das dúvidas resolvi testar os códigos:

Resultado foi:

Bubble-&gt;Amostragem 0&#58; 210ms
Bubble-&gt;Amostragem 1&#58; 200ms
Bubble-&gt;Amostragem 2&#58; 201ms
Bubble-&gt;Amostragem 3&#58; 190ms
Bubble-&gt;Amostragem 4&#58; 210ms
Bubble-&gt;Average&#58; 202ms
Bubble-&gt;Output&#58; 1,2,3,4,5,6,7,8,9,
Quicksort-&gt;Amostragem 0&#58; 381ms
Quicksort-&gt;Amostragem 1&#58; 380ms
Quicksort-&gt;Amostragem 2&#58; 411ms
Quicksort-&gt;Amostragem 3&#58; 370ms
Quicksort-&gt;Amostragem 4&#58; 381ms
Quicksort-&gt;Average&#58; 384ms
Quicksort-&gt;Output&#58; 1,2,3,4,5,6,7,8,9,

O código que usei pra chegar a isso foi:

public class Bench &#123;
    public static void main&#40;String &#91;&#93; argvs&#41; throws Exception &#123;
        String &#91;&#93; abc = new String&#91;&#93; &#123;&quot;9&quot;, &quot;3&quot;, &quot;1&quot;, &quot;2&quot;, &quot;4&quot;, &quot;8&quot;, &quot;6&quot;, &quot;7&quot;, &quot;5&quot;&#125;;
        Bench   bench = new Bench&#40;&#41;;
        int       len = abc.length;
        int     total = 0;
        int iteration = 5;
        // bubble
        for&#40;int x = 0; x &lt; iteration; x++&#41; &#123;
            long str = System.currentTimeMillis&#40;&#41;;
            for&#40;int y = 0; y &lt; 100000; y++&#41; &#123;
                bench.bubble&#40;abc&#41;;
            &#125;
            long end = System.currentTimeMillis&#40;&#41;;
            total   += end - str;
            System.out.println&#40;&quot;Bubble-&gt;Amostragem &quot; + x + &quot;&#58; &quot; + &#40;end - str&#41; + &quot;ms&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;Bubble-&gt;Average&#58; &quot; + Math.round&#40;total / iteration&#41; + &quot;ms&quot;&#41;;
        System.out.print&#40;&quot;Bubble-&gt;Output&#58; &quot;&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + &quot;,&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;&quot;&#41;;
        // quicksort
        total = 0;
        for&#40;int x = 0; x &lt; iteration; x++&#41; &#123;
            long str = System.currentTimeMillis&#40;&#41;;
            for&#40;int y = 0; y &lt; 100000; y++&#41; &#123;
                bench.quicksort&#40;0, len - 1, abc&#41;;
            &#125;
            long end = System.currentTimeMillis&#40;&#41;;
            total   += end - str;
            System.out.println&#40;&quot;Quicksort-&gt;Amostragem &quot; + x + &quot;&#58; &quot; + &#40;end - str&#41; + &quot;ms&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;Quicksort-&gt;Average&#58; &quot; + Math.round&#40;total / iteration&#41; + &quot;ms&quot;&#41;;
        System.out.print&#40;&quot;Quicksort-&gt;Output&#58; &quot;&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + &quot;,&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;&quot;&#41;;
    &#125;
    void troca&#40;String array&#91;&#93;, int i, int j&#41; &#123;
        String aux = array&#91;i&#93;; 
        array&#91;i&#93;   = array&#91;j&#93;; 
        array&#91;j&#93;   = aux; 
    &#125; 
    void quicksort&#40;int p, int q, String array&#91;&#93;&#41; &#123; 
        if &#40;p &lt; q&#41; &#123;
            int x = particao&#40;p, q, array&#41;; 
            quicksort&#40;p, x - 1, array&#41;; 
            quicksort&#40;x + 1, q, array&#41;; 
        &#125; 
    &#125; 
    int particao&#40;int p, int q, String array&#91;&#93;&#41;&#123; 
        int j = p - 1; 
        String aux = array&#91;q&#93;; 
        for &#40;int i = p; i &lt;= q; i++&#41;&#123; 
            if &#40;array&#91;i&#93;.compareTo&#40;aux&#41; &lt;= 0&#41; troca&#40;array, i, ++j&#41;; 
        &#125; 
        return j; 
    &#125;
    String &#91;&#93; bubble&#40;String &#91;&#93; strArray&#41; throws Exception &#123;
        int j;
        int limit = strArray.length;
        int    st = -1;
        while&#40;st &lt; limit&#41; &#123;
            st++;
            limit--;
            boolean swapped = false;
            for&#40;j = st; j &lt; limit; j++&#41; &#123;
                int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                    strArrayAt = strArrayAt - 32;
                &#125;
                int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                    strArrayAtPlusOne = strArrayAtPlusOne - 32;
                &#125;
                if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                    String tempValue = strArray&#91;j&#93;;
                    strArray&#91;j&#93;      = strArray&#91;j + 1&#93;;
                    strArray&#91;j + 1&#93;  = tempValue;
                    swapped = true;
                &#125;
            &#125;
            for&#40;j = limit; --j &gt;= st;&#41; &#123;
                int strArrayAt = &#40;int&#41; strArray&#91;j&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                    strArrayAt = strArrayAt - 32;
                &#125;
                int strArrayAtPlusOne = &#40;int&#41; strArray&#91;j + 1&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                    strArrayAtPlusOne = strArrayAtPlusOne - 32;
                &#125;
                if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                    String tempValue = strArray&#91;j&#93;;
                    strArray&#91;j&#93;      = strArray&#91;j + 1&#93;;
                    strArray&#91;j + 1&#93;  = tempValue;
                    swapped = true;
                &#125;
            &#125;
        &#125;
        return strArray;
    &#125;
&#125;

Por um segundo pensei que eu estivesse errado sobre a velocidade…mas estava certo :slight_smile:
Vivendo e aprendendo :wink:

EDIT: Tinha esquecido de zerar o “total” e por isso nao estava correto o resultado.[/quote]

Detalhe: esse codigo meu do bubble era pra ser bi-direcional, mas pelo que vi, fiz merda.

Comentando o laco for:

for&#40;j = limit; --j &gt;= st;&#41; &#123;

Funciona normalmente e a média cai pela metade, ficando ainda mais rápido.

Aff, olhando meu bubble sort melhor agora, dá até nojo.

Enfim, minha solução (obvio que o bubble nao fui eu que inventei né, so estou sugerindo) é mais rápida, porém o meu código está nojento (ver variavel swapped que nao serve pra nada por exemplo).

Vou re-escrever esse lixo e posto em 5 mins.

[quote=“mavi”]Aff, olhando meu bubble sort melhor agora, dá até nojo.

Enfim, minha solução (obvio que o bubble nao fui eu que inventei né, so estou sugerindo) é mais rápida, porém o meu código está nojento (ver variavel swapped que nao serve pra nada por exemplo).

Vou re-escrever esse lixo e posto em 5 mins.[/quote]

Ah, estava sujo mas nem tanto, enfim o codigo de comparacao estava ruim tambem…esse esta melhor, com o bubble bidirecional escrito da maneira certa, deu o seguinte:

Bubble-&gt;Amostragem 0&#58; 130ms
Bubble-&gt;Amostragem 1&#58; 100ms
Bubble-&gt;Amostragem 2&#58; 90ms
Bubble-&gt;Amostragem 3&#58; 130ms
Bubble-&gt;Amostragem 4&#58; 90ms
Bubble-&gt;Average&#58; 108ms
Bubble-&gt;Output&#58; 3,4,5,6,7,8,
Quicksort-&gt;Amostragem 0&#58; 191ms
Quicksort-&gt;Amostragem 1&#58; 180ms
Quicksort-&gt;Amostragem 2&#58; 190ms
Quicksort-&gt;Amostragem 3&#58; 180ms
Quicksort-&gt;Amostragem 4&#58; 181ms
Quicksort-&gt;Average&#58; 184ms
Quicksort-&gt;Output&#58; 3,4,5,6,7,8,

O codigo usado foi:

public class Bench &#123;
    public static void main&#40;String &#91;&#93; argvs&#41; throws Exception &#123;
        String &#91;&#93; ori = new String&#91;&#93; &#123;&quot;8&quot;, &quot;5&quot;, &quot;7&quot;, &quot;6&quot;, &quot;4&quot;, &quot;3&quot;&#125;;
        String &#91;&#93; abc = ori.clone&#40;&#41;;
        Bench   bench = new Bench&#40;&#41;;
        int       len = abc.length;
        int     total = 0;
        int iteration = 5;
        long str, end;
        // bubble
        for&#40;int x = 0; x &lt; iteration; x++&#41; &#123;
            str = System.currentTimeMillis&#40;&#41;;
            for&#40;int y = 0; y &lt; 100000; y++&#41; &#123;
                bench.bubble&#40;abc&#41;;
            &#125;
            end    = System.currentTimeMillis&#40;&#41;;
            total += end - str;
            System.out.println&#40;&quot;Bubble-&gt;Amostragem &quot; + x + &quot;&#58; &quot; + &#40;end - str&#41; + &quot;ms&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;Bubble-&gt;Average&#58; &quot; + Math.round&#40;total / iteration&#41; + &quot;ms&quot;&#41;;
        System.out.print&#40;&quot;Bubble-&gt;Output&#58; &quot;&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + &quot;,&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;&quot;&#41;;
        // quicksort
        abc   = ori.clone&#40;&#41;;
        total = 0;
        for&#40;int x = 0; x &lt; iteration; x++&#41; &#123;
            str = System.currentTimeMillis&#40;&#41;;
            for&#40;int y = 0; y &lt; 100000; y++&#41; &#123;
                bench.quicksort&#40;0, len - 1, abc&#41;;
            &#125;
            end    = System.currentTimeMillis&#40;&#41;;
            total += end - str;
            System.out.println&#40;&quot;Quicksort-&gt;Amostragem &quot; + x + &quot;&#58; &quot; + &#40;end - str&#41; + &quot;ms&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;Quicksort-&gt;Average&#58; &quot; + Math.round&#40;total / iteration&#41; + &quot;ms&quot;&#41;;
        System.out.print&#40;&quot;Quicksort-&gt;Output&#58; &quot;&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + &quot;,&quot;&#41;;
        &#125;
        System.out.println&#40;&quot;&quot;&#41;;
    &#125;
    void troca&#40;String array&#91;&#93;, int x, int y&#41; &#123;
        String aux = array&#91;x&#93;; 
        array&#91;x&#93;   = array&#91;y&#93;; 
        array&#91;y&#93;   = aux; 
    &#125; 
    void quicksort&#40;int p, int q, String array&#91;&#93;&#41; &#123; 
        if&#40;p &lt; q&#41; &#123;
            int x = particao&#40;p, q, array&#41;; 
            quicksort&#40;p, x - 1, array&#41;; 
            quicksort&#40;x + 1, q, array&#41;; 
        &#125; 
    &#125; 
    int particao&#40;int p, int q, String array&#91;&#93;&#41; &#123;
        int j = p - 1; 
        String aux = array&#91;q&#93;; 
        for&#40;int i = p; i &lt;= q; i++&#41;&#123; 
            if &#40;array&#91;i&#93;.compareTo&#40;aux&#41; &lt;= 0&#41; 
                troca&#40;array, i, ++j&#41;; 
        &#125; 
        return j; 
    &#125;
    String &#91;&#93; bubble&#40;String &#91;&#93; strArray&#41; throws Exception &#123;
        int   cur = 0;
        int limit = strArray.length - 1;
        int start = 0;
        while&#40;start &lt; limit&#41; &#123;
            for&#40;cur = start; cur &lt; limit; cur++&#41; &#123;
                int strArrayAt = &#40;int&#41; strArray&#91;cur&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                    strArrayAt = strArrayAt - 32;
                &#125;
                int strArrayAtPlusOne = &#40;int&#41; strArray&#91;cur + 1&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                    strArrayAtPlusOne = strArrayAtPlusOne - 32;
                &#125;
                if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                    String tempValue  = strArray&#91;cur&#93;;
                    strArray&#91;cur&#93;     = strArray&#91;cur + 1&#93;;
                    strArray&#91;cur + 1&#93; = tempValue;
                &#125;
            &#125;
            for&#40;cur = limit; --cur &gt;= start;&#41; &#123;
                int strArrayAt = &#40;int&#41; strArray&#91;cur&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAt &gt;= 97 &amp;&amp; strArrayAt &lt;= 122&#41; &#123;
                    strArrayAt = strArrayAt - 32;
                &#125;
                int strArrayAtPlusOne = &#40;int&#41; strArray&#91;cur + 1&#93;.charAt&#40;0&#41;;
                if&#40;strArrayAtPlusOne &gt;= 97 &amp;&amp; strArrayAtPlusOne &lt;= 122&#41; &#123;
                    strArrayAtPlusOne = strArrayAtPlusOne - 32;
                &#125;
                if&#40;strArrayAt &gt; strArrayAtPlusOne&#41; &#123;
                    String tempValue = strArray&#91;cur&#93;;
                    strArray&#91;cur&#93;      = strArray&#91;cur + 1&#93;;
                    strArray&#91;cur + 1&#93;  = tempValue;
                &#125;
            &#125;
            start++;
            limit--;
        &#125;
        return strArray;
    &#125;
&#125;

O bubble bidirecional ainda esta ganhando.

Se nao me engano, no site da sun tinha 3 applets, cada um ordenava de um jeito…e acho que o bi era o mais rapido (motivo de eu usar ele).

Abs.

Cacete, to floodando aqui hoje :stuck_out_tongue:

Achei o link:

http://java.sun.com/applets/jdk/1.4/demo/applets/SortDemo/example1.html

Detalhe: o bubble sort parece estar perdendo nesse caso.

Talvez tenha vantagem e desvantagem em bubble X quicksort, ou seu algoritmo esteja mal escrito (pra ser sincero nem li ele direito, so olhei por cima).

Talvez o bubble bidi execute mais rapido que o quick em iteracoes pequenas (tipo a meia duzia de numeros que coloquei pra ordenar), mas peque na escalabilidade (ordenar em milhoes), enquanto o sort apanhe nos dados pequenos, mas não exponencie tão alto…

Enfim, sei lá, mas vou parar de brincar com os códigos por hoje por que preciso dormir :slight_smile:

Esse é o bubble bidirecional.

O quicksort provavelmente é linear.

http://www.cs.rit.edu/~atk/Java/Sorting/sorting.html

Mais um link legal.

Vendo o O-E Tran. Sort e o Shear Sort, só tenho uma coisa a dizer:

PQP

Absolutamente foda.

O shear sort deve ser no minimo 5 vezes mais rapido que o quick, que é no minimo 4 vezes mais rapido que o bubble (nos testes que fiz, por que varia obviamente de acordo com a quantidade)

Enfim…
Acho que vou brincar de fazer algoritmo rapido depois, pra ver se aproximo pelo menos do Shear Sort…(até parece né, a matemática envolvida é monstruosa, mas enfim, é legal “brincar” disso)