Ordem alfabética

36 respostas
O

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?

36 Respostas

R

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
  • ???
O

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:

R

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

Ex:
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(lista);
        
        System.out.println(lista);        
    }    
}

A saida vai estar ordenada...

Te ajudou...?

M
"renan_daniel":
Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort. Ex:
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(lista);
        
        System.out.println(lista);        
    }    
}

A saida vai estar ordenada...

Te ajudou...?

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

public String [] sort(String [] strArray) throws Exception {
    int j;
    int limit = strArray.length;
    int    st = -1;
    while(st < limit) {
        st++;
        limit--;
        boolean swapped = false;
        for(j = st; j < limit; j++) {
            int strArrayAt = (int) strArray[j].charAt(0);
            if(strArrayAt >= 97 && strArrayAt <= 122) {
                strArrayAt = strArrayAt - 32;
            }
            int strArrayAtPlusOne = (int) strArray[j + 1].charAt(0);
            if(strArrayAtPlusOne >= 97 && strArrayAtPlusOne <= 122) {
                strArrayAtPlusOne = strArrayAtPlusOne - 32;
            }
            if(strArrayAt > strArrayAtPlusOne) {
                String tempValue = strArray[j];
                strArray[j]      = strArray[j + 1];
                strArray[j + 1]  = tempValue;
                swapped = true;
            }
        }
        for(j = limit; --j >= st;) {
            int strArrayAt = (int) strArray[j].charAt(0);
            if(strArrayAt >= 97 && strArrayAt <= 122) {
                strArrayAt = strArrayAt - 32;
            }
            int strArrayAtPlusOne = (int) strArray[j + 1].charAt(0);
            if(strArrayAtPlusOne >= 97 && strArrayAtPlusOne <= 122) {
                strArrayAtPlusOne = strArrayAtPlusOne - 32;
            }
            if(strArrayAt > strArrayAtPlusOne) {
                String tempValue = strArray[j];
                strArray[j]      = strArray[j + 1];
                strArray[j + 1]  = tempValue;
                swapped = true;
            }
        }
    }
    return strArray;
}
O

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!

J
Olá, renam, não precisa fazer o for para preencher a List com os objetos do array. Basta fazer assim:
import java.util.*;

public class teste &#123;
	public static void main&#40;String&#91;&#93; args&#41; &#123;
		String a&#91;&#93; = &#123;&quot;Maria&quot;, &quot;Joao&quot;, &quot;Renan&quot;&#125;;

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

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

		System.out.println&#40;lista&#41;;
	&#125;
&#125;
"omegatiger":
Poderia me explicar sobre os valores que apresentou neste seu Sort?

"if(strArrayAt >= 97 && strArrayAt <= 122)"


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...

M

“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!

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

R
[quote="jack_-_ganzha"]Olá, renam, não precisa fazer o for para preencher a List com os objetos do array. Basta fazer assim:
import java.util.*;

public class teste &#123;
	public static void main&#40;String&#91;&#93; args&#41; &#123;
		String a&#91;&#93; = &#123;&quot;Maria&quot;, &quot;Joao&quot;, &quot;Renan&quot;&#125;;

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

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

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

Essa eu naum conhecia, valeu...

F
"mavi":
"renan_daniel":
Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort. Ex:
import java.util.*;


public class teste &#123;   
    public static void main&#40;String&#91;&#93; args&#41; &#123;
        String a&#91;&#93; = &#123;&quot;Maria&quot;, &quot;Joao&quot;, &quot;Renan&quot;&#125;;
        ArrayList lista = new ArrayList&#40;&#41;;
        for&#40;int i = 0; i &lt; a.length; i++&#41; &#123;
           lista.add&#40;a&#91;i&#93;&#41;;
        &#125;
        
        Collections.sort&#40;lista&#41;;
        
        System.out.println&#40;lista&#41;;        
    &#125;    
&#125;

A saida vai estar ordenada...

Te ajudou...?

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;

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:

azzzzz aa

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;;
O
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...
M
"Felipe":
"mavi":
"renan_daniel":
Cara o que vc pode estar fazendo é jogando em um ArrayList e executando o sort. Ex:
import java.util.*;


public class teste &#123;   
    public static void main&#40;String&#91;&#93; args&#41; &#123;
        String a&#91;&#93; = &#123;&quot;Maria&quot;, &quot;Joao&quot;, &quot;Renan&quot;&#125;;
        ArrayList lista = new ArrayList&#40;&#41;;
        for&#40;int i = 0; i &lt; a.length; i++&#41; &#123;
           lista.add&#40;a&#91;i&#93;&#41;;
        &#125;
        
        Collections.sort&#40;lista&#41;;
        
        System.out.println&#40;lista&#41;;        
    &#125;    
&#125;

A saida vai estar ordenada...

Te ajudou...?

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;

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:

azzzzz aa

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;;

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.

F

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…

M

“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…

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;"9", "3", "1", "2", "4", "8", "6", "7", "5"&#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;"Bubble-&gt;Amostragem " + x + "&#58; " + &#40;end - str&#41; + "ms"&#41;;
        &#125;
        System.out.println&#40;"Bubble-&gt;Average&#58; " + Math.round&#40;total / iteration&#41; + "ms"&#41;;
        System.out.print&#40;"Bubble-&gt;Output&#58; "&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + ","&#41;;
        &#125;
        System.out.println&#40;""&#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;"Quicksort-&gt;Amostragem " + x + "&#58; " + &#40;end - str&#41; + "ms"&#41;;
        &#125;
        System.out.println&#40;"Quicksort-&gt;Average&#58; " + Math.round&#40;total / iteration&#41; + "ms"&#41;;
        System.out.print&#40;"Quicksort-&gt;Output&#58; "&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + ","&#41;;
        &#125;
        System.out.println&#40;""&#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.

M

“mavi”:
“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…

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;"9", "3", "1", "2", "4", "8", "6", "7", "5"&#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;"Bubble-&gt;Amostragem " + x + "&#58; " + &#40;end - str&#41; + "ms"&#41;;
        &#125;
        System.out.println&#40;"Bubble-&gt;Average&#58; " + Math.round&#40;total / iteration&#41; + "ms"&#41;;
        System.out.print&#40;"Bubble-&gt;Output&#58; "&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + ","&#41;;
        &#125;
        System.out.println&#40;""&#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;"Quicksort-&gt;Amostragem " + x + "&#58; " + &#40;end - str&#41; + "ms"&#41;;
        &#125;
        System.out.println&#40;"Quicksort-&gt;Average&#58; " + Math.round&#40;total / iteration&#41; + "ms"&#41;;
        System.out.print&#40;"Quicksort-&gt;Output&#58; "&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + ","&#41;;
        &#125;
        System.out.println&#40;""&#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.

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.

M

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.

M

“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.

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;"8", "5", "7", "6", "4", "3"&#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;"Bubble-&gt;Amostragem " + x + "&#58; " + &#40;end - str&#41; + "ms"&#41;;
        &#125;
        System.out.println&#40;"Bubble-&gt;Average&#58; " + Math.round&#40;total / iteration&#41; + "ms"&#41;;
        System.out.print&#40;"Bubble-&gt;Output&#58; "&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + ","&#41;;
        &#125;
        System.out.println&#40;""&#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;"Quicksort-&gt;Amostragem " + x + "&#58; " + &#40;end - str&#41; + "ms"&#41;;
        &#125;
        System.out.println&#40;"Quicksort-&gt;Average&#58; " + Math.round&#40;total / iteration&#41; + "ms"&#41;;
        System.out.print&#40;"Quicksort-&gt;Output&#58; "&#41;;
        for&#40;int i = 0; i &lt; len; i++&#41; &#123;
            System.out.print&#40;abc&#91;i&#93; + ","&#41;;
        &#125;
        System.out.println&#40;""&#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.

M

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:

M

Esse é o bubble bidirecional.

O quicksort provavelmente é linear.

M

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)

F

tipo, o seu bublesort esta sendo amis rapido pelos seguintes motivos:

:arrow: a comparacao, vc esta comparando soh a primeira letra, enquanto eu estou chamando um metodo da classe String para fazer isso, esse metodo vai continuar comparando se as letras forem iguais, e lembre-se chamada a metodo tb consome tempo

:arrow: esse ex eu fiz como um ex, eu postei desse jeito pra vcs verem como funciona, desse jeito fica MUITO mais rapido:

public void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#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;&#123;
    String aux2 = array&#91;i&#93;;
    array&#91;i&#93; = array&#91;++j&#93;;
    array&#91;j&#93; = aux2;
   &#125;
  &#125;
  quicksort&#40;p, j - 1, array&#41;;
  quicksort&#40;j + 1, q, array&#41;;
 &#125;
&#125;

e tipo, teste denovo, soh q agora com o seguinte array:

String array&#91;&#93; = &#123;"aaz", "aa16", "aah", "a716", "bah", "182", "132"&#125;;

vc vai verificar q o seu codigo vai reconhecer “aaz” como igual a “aa16”…

M

“Felipe”:
tipo, o seu bublesort esta sendo amis rapido pelos seguintes motivos:

:arrow: a comparacao, vc esta comparando soh a primeira letra, enquanto eu estou chamando um metodo da classe String para fazer isso, esse metodo vai continuar comparando se as letras forem iguais, e lembre-se chamada a metodo tb consome tempo

:arrow: esse ex eu fiz como um ex, eu postei desse jeito pra vcs verem como funciona, desse jeito fica MUITO mais rapido:

public void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#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;&#123;
    String aux2 = array&#91;i&#93;;
    array&#91;i&#93; = array&#91;++j&#93;;
    array&#91;j&#93; = aux2;
   &#125;
  &#125;
  quicksort&#40;p, j - 1, array&#41;;
  quicksort&#40;j + 1, q, array&#41;;
 &#125;
&#125;

e tipo, teste denovo, soh q agora com o seguinte array:

String array&#91;&#93; = &#123;"aaz", "aa16", "aah", "a716", "bah", "182", "132"&#125;;

vc vai verificar q o seu codigo vai reconhecer “aaz” como igual a “aa16”…

Depois testo essa sua versão, e sobre a ordenação, sim, foi o que eu disse, mas nesse caso a solucao teria sido a melhor (ordenar so a primeira letra), ou ate mesmo se fosse um int [], afinal, é só o número pra comparar…depois vejo se testo mesmo…depois de ver o shear sort não tem nem por que discutir velocidade de bubble e quick :slight_smile:

Além do que a fórmula diz tudo:

Bubble Sort is a sequential algorithm, with an average case time of O&#40;n2&#41;. 
Quick Sort is a sequential algorithm, with an average case time of O&#40;n log n&#41;. 
Odd-Even Transposition Sort is a parallel algorithm, with an worst case time of O&#40;n&#41;, running on n processors. Its absolute speed up is O&#40;log n&#41;, so its efficiency is O&#40;&#40;log n&#41;/n&#41;. 
Shear Sort is a parallel algorithm, with an worst case time of O&#40;n1/2 log n&#41;, running on n processors. Its absolute speed up is O&#40;n1/2&#41;, so its efficiency is O&#40;1/n1/2&#41;.
F

jah adiantando com um teste q eu fiz:

Buble tempo&#58; 1499
Array&#58;
182 132 aaz aa16 aah a716 bah
Quicksort tempo&#58; 1248
Array&#58;
132 182 a716 aa16 aah aaz bah

OBS: note que o seu buble sort n organiza apartir da segunda letra, ao contrario do quicksort, por isso ele esta conseguindo um desempenho um pouco maior do q um bublesort teria, pois n esta organizando devidamente…

cheguei nisso com esse codigo:

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  String array&#91;&#93;, copia&#91;&#93; = &#123;"aaz", "aa16", "aah", "a716", "bah", "182", "132"&#125;;
  long ms = 0;
  array = new String&#91;copia.length&#93;;
  copia&#40;array, copia&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  for &#40;int i = 0; i &lt; 1000000; i++&#41;&#123;
   copia&#40;array, copia&#41;;
   bubble&#40;array&#41;;
  &#125;
  System.out.println&#40;"Buble tempo&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
  System.out.println&#40;"Array&#58; "&#41;;
  for &#40;int i = 0; i &lt; array.length; i++&#41; System.out.print&#40;array&#91;i&#93; + " "&#41;;
  System.out.println&#40;&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  for &#40;int i = 0; i &lt; 1000000; i++&#41;&#123;
   copia&#40;array, copia&#41;;
   quicksort&#40;0, array.length - 1, array&#41;;
  &#125;
  System.out.println&#40;"Quicksort tempo&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
  System.out.println&#40;"Array&#58; "&#41;;
  for &#40;int i = 0; i &lt; array.length; i++&#41; System.out.print&#40;array&#91;i&#93; + " "&#41;;
  System.out.println&#40;&#41;;
 &#125;
 public static void copia&#40;String array&#91;&#93;, String copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41; array&#91;i&#93; = copia&#91;i&#93;;
 &#125;
 public static void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#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;&#123;
    String aux2 = array&#91;i&#93;;
    array&#91;i&#93; = array&#91;++j&#93;;
    array&#91;j&#93; = aux2;
   &#125;
  &#125;
  quicksort&#40;p, j - 1, array&#41;;
  quicksort&#40;j + 1, q, array&#41;;
 &#125;
&#125; 
 public static String&#91;&#93; bubble&#40;String&#91;&#93; strArray&#41;&#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;

OBS: tanto no quicksort como no buble eu copiei o array antigo, por como em arrays eh passado por referencia, n faz sentido organizar um array jah organizado, se for organizar arrays jah organizados o bubble sort provavelmente teria um desempenho mais proximo (ou talvez ateh melhor) q o quicksort, jah q o quicksort faz trocas com elementos iguals enquanto o bubblesort nao, por isso q eu n digo q o quicksort eh o mais rapido, e sim um dos mais rapidos, pq dependendo da situacao pode ser um outro metodo de ordenacao o mais apropriado :grin:

M

“Felipe”:
jah adiantando com um teste q eu fiz:

Buble tempo&#58; 1499
Array&#58;
182 132 aaz aa16 aah a716 bah
Quicksort tempo&#58; 1248
Array&#58;
132 182 a716 aa16 aah aaz bah

OBS: note que o seu buble sort n organiza apartir da segunda letra, ao contrario do quicksort, por isso ele esta conseguindo um desempenho um pouco maior do q um bublesort teria, pois n esta organizando devidamente…

cheguei nisso com esse codigo:

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  String array&#91;&#93;, copia&#91;&#93; = &#123;"aaz", "aa16", "aah", "a716", "bah", "182", "132"&#125;;
  long ms = 0;
  array = new String&#91;copia.length&#93;;
  copia&#40;array, copia&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  for &#40;int i = 0; i &lt; 1000000; i++&#41;&#123;
   copia&#40;array, copia&#41;;
   bubble&#40;array&#41;;
  &#125;
  System.out.println&#40;"Buble tempo&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
  System.out.println&#40;"Array&#58; "&#41;;
  for &#40;int i = 0; i &lt; array.length; i++&#41; System.out.print&#40;array&#91;i&#93; + " "&#41;;
  System.out.println&#40;&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  for &#40;int i = 0; i &lt; 1000000; i++&#41;&#123;
   copia&#40;array, copia&#41;;
   quicksort&#40;0, array.length - 1, array&#41;;
  &#125;
  System.out.println&#40;"Quicksort tempo&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
  System.out.println&#40;"Array&#58; "&#41;;
  for &#40;int i = 0; i &lt; array.length; i++&#41; System.out.print&#40;array&#91;i&#93; + " "&#41;;
  System.out.println&#40;&#41;;
 &#125;
 public static void copia&#40;String array&#91;&#93;, String copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41; array&#91;i&#93; = copia&#91;i&#93;;
 &#125;
 public static void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#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;&#123;
    String aux2 = array&#91;i&#93;;
    array&#91;i&#93; = array&#91;++j&#93;;
    array&#91;j&#93; = aux2;
   &#125;
  &#125;
  quicksort&#40;p, j - 1, array&#41;;
  quicksort&#40;j + 1, q, array&#41;;
 &#125;
&#125; 
 public static String&#91;&#93; bubble&#40;String&#91;&#93; strArray&#41;&#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;

OBS: tanto no quicksort como no buble eu copiei o array antigo, por como em arrays eh passado por referencia, n faz sentido organizar um array jah organizado, se for organizar arrays jah organizados o bubble sort provavelmente teria um desempenho mais proximo (ou talvez ateh melhor) q o quicksort, jah q o quicksort faz trocas com elementos iguals enquanto o bubblesort nao, por isso q eu n digo q o quicksort eh o mais rapido, e sim um dos mais rapidos, pq dependendo da situacao pode ser um outro metodo de ordenacao o mais apropriado :grin:

Sim, no ultimo post que coloquei, usei cópia ( .clone() ) pois estava usando por referencia no comeco e nem tinha percebido…tipo, na primeira rodada ja estava tudo organizado e ai o bench era inutil, mas no ultimo codigo que coloquei esta usando clonando o negocio e fazendo tudo direitinho…

O meu bubble so ve o primeiro caractere mesmo.

Vou rodar seu codigo agora aqui e tentar escrever alguma coisa mais rapida so por diversao mesmo (com certeza nao vou conseguir, mas enfim…)…

M

Ah, agora que vi o que voce quis dizer, realmente, ele estava usando o mesmo array ja ordenado…ugh, foi o sono :slight_smile:

Mas…(versao ja esta vindo)

M

“mavi”:
Ah, agora que vi o que voce quis dizer, realmente, ele estava usando o mesmo array ja ordenado…ugh, foi o sono :slight_smile:

Mas…(versao ja esta vindo)

public class Bench &#123; 
    public static void main&#40;String &#91;&#93; args&#41; &#123;
        String &#91;&#93; array = &#123;"aaz", "aa16", "aah", "a716", "bah", "182", "132"&#125;; 
        String &#91;&#93; copia = array.clone&#40;&#41;;
        long str, end;
        str = System.currentTimeMillis&#40;&#41;; 
        for&#40;int i = 0; i &lt; 250000; i++&#41; &#123;
            copia = array.clone&#40;&#41;;
            bubble&#40;copia&#41;; 
        &#125; 
        end = System.currentTimeMillis&#40;&#41;;
        System.out.println&#40;"Buble tempo&#58; " + &#40;end - str&#41;&#41;; 
        System.out.println&#40;"Array&#58; "&#41;; 
        for&#40;int i = 0; i &lt; array.length; i++&#41;
            System.out.print&#40;array&#91;i&#93; + " "&#41;; 
        System.out.println&#40;&#41;; 
        str = System.currentTimeMillis&#40;&#41;; 
        for&#40;int i = 0; i &lt; 250000; i++&#41; &#123;
            copia = array.clone&#40;&#41;;
            quicksort&#40;0, array.length - 1, array&#41;; 
        &#125; 
        end = System.currentTimeMillis&#40;&#41;;
        System.out.println&#40;"Quicksort tempo&#58; " + &#40;end - str&#41;&#41;; 
        System.out.println&#40;"Array&#58; "&#41;; 
        for&#40;int i = 0; i &lt; array.length; i++&#41; 
            System.out.print&#40;array&#91;i&#93; + " "&#41;; 
        System.out.println&#40;&#41;; 
    &#125; 
    public static void quicksort&#40;int p, int q, String array&#91;&#93;&#41;&#123; 
        if&#40;p &lt; q&#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; &#123;
                String aux2 = array&#91;i&#93;; 
                array&#91;i&#93; = array&#91;++j&#93;; 
                array&#91;j&#93; = aux2; 
            &#125; 
        &#125; 
        quicksort&#40;p, j - 1, array&#41;; 
        quicksort&#40;j + 1, q, array&#41;; 
    &#125; 
    &#125; 
    public static String&#91;&#93; bubble&#40;String&#91;&#93; strArray&#41;&#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 ainda está ganhando, MAS, reconheco que ele so ordena o primeiro caractere, e por isso, apesar de ser mais rápido NESSE caso, é obviamente menos eficiente (se comparasse todos caracteres, nesse caso, em que a string tem em media 3 letras, provavelmente demoraria o triplo).

Agora vou tentar fazer uma versao fuçada de um algoritmo que imaginei na hora fertil do dia (banheiro).

M

Detalhes constadados:

#1: Em um char só (“a”, “b”, “z”, “i”, “u”, “o”) a performance é quase igual (em um array pequeno, pois o bubble quanto maior o array, mais lento).
#2: A sua implementação considera que o ‘E’ vem antes do ‘a’ (normalmente isso não é bom, depende da aplicação).

F

tipo, vc n pode esquecer q o algoritimo eh de ordenacao, e nao de comparacao de Strings, portanto qndo se vai fazer ot este de qual algoritimo eh mais rapido, se usa int, dai eh soh x > y e pronto…

e como vc disse, o buble sort fica lento com arrays muito grandes, depois posto um teste aki para ilustrar isso… por isso q eu prefiro o quicksort, pq com arrays pequenos, a diferenca vai ser de alguns ms (talvez alguns poucos nano segundos), algo q nem vai dar pra notar a diferenca, e agora se o array tiver, por ex 10000 elementos, a deferenca vai ser grande, de varios segundos, dependendo do computador talvez ateh minutos!!!

e como eu jah disse, em cada situacao um metodo eh mais indicado, por ex, se vc tiver uma lista q jah esta organizada, e vc quiser adicionar um novo elemento na sequencia, se vc fizer um insertionsort sem o loop externo, vai ser MUITO mais rapido do q qquer outro metodo citado neste topico!

F

fiz um teste agora usando inteiros em q a diferenca ficou bem evidente:

quicksort levou 33 milisegundos e bublesort levou mais de 84 segundos, uma diferenca maior q 2000x!!!

usei esse codigo pra esse teste:

OBS: alterei seu codigo para funcionar com inteiros, caso eu tenha cometido algum equivoco ou deserrumado algo sem querer me avise :wink:

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  long ms;
  int array&#91;&#93;, copia&#91;&#93; = geraArray&#40;100000&#41;;
  array = new int&#91;copia.length&#93;;
  copia&#40;array, copia&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  quicksort&#40;0, array.length - 1, array&#41;;
  System.out.println&#40;"Quicksort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
  copia&#40;array, copia&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  bubble&#40;array&#41;;
  System.out.println&#40;"Bubble&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
 &#125;
 public static void copia&#40;int array&#91;&#93;, int copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41;&#123;
   array&#91;i&#93; = copia&#91;i&#93;;
  &#125;
 &#125;
 public static int&#91;&#93; geraArray&#40;int size&#41;&#123;
  int array&#91;&#93; = new int&#91;size&#93;;
  for &#40;int i = 0; i &lt; size; i++&#41;&#123;
   array&#91;i&#93; = &#40;int&#41;&#40;Math.random&#40;&#41; * size&#41;;
  &#125;
  return array;
 &#125;
 public static void quicksort&#40;int p, int q, int array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#41;&#123;
  int j = p - 1;
  int aux = array&#91;q&#93;;
  for &#40;int i = p; i &lt;= q; i++&#41;&#123;
   if &#40;array&#91;i&#93; &lt;= aux&#41;&#123;
    int aux2 = array&#91;i&#93;;
    array&#91;i&#93; = array&#91;++j&#93;;
    array&#91;j&#93; = aux2;
   &#125;
  &#125;
  quicksort&#40;p, j - 1, array&#41;;
  quicksort&#40;j + 1, q, array&#41;;
 &#125;
&#125; 
 public static int&#91;&#93; bubble&#40;int&#91;&#93; intArray&#41;&#123;
        int   cur = 0;
        int limit = intArray.length - 1;
        int start = 0;
        while&#40;start &lt; limit&#41; &#123;
            for&#40;cur = start; cur &lt; limit; cur++&#41; &#123;
                if&#40;intArray&#91;cur&#93; &gt; intArray&#91;cur + 1&#93;&#41; &#123;
                    int tempValue  = intArray&#91;cur&#93;;
                    intArray&#91;cur&#93;     = intArray&#91;cur + 1&#93;;
                    intArray&#91;cur + 1&#93; = tempValue;
                &#125;
            &#125;
            for&#40;cur = limit; --cur &gt;= start;&#41; &#123;
                if&#40;intArray&#91;cur&#93; &gt; intArray&#91;cur + 1&#93;&#41; &#123;
                    int tempValue = intArray&#91;cur&#93;;
                    intArray&#91;cur&#93;      = intArray&#91;cur + 1&#93;;
                    intArray&#91;cur + 1&#93;  = tempValue;
                &#125;
            &#125;
            start++;
            limit--;
        &#125;
        return intArray;
    &#125; 
&#125;

outra observacao, vc n precisa retornar o array, pois os arrays sao passados por referencia, entaum as modificacoes feitas no metodo vao afetar o array original (por isso q eh feita uma copia)…

qndo estavamos comparando strings a diferenca era pequena (e o bublesort chegava a ser mais rapido), pq alem de estarmos usando arrays muito pequenos (onde ainda assim o quicksort eh mais rapido, a nao ser claro se for um array de 1 ou 2 elementos), vc estava comparando apenas o primeiro caractere, como eu jah disse inumeras vezes, vc tb pode comparar apenas o primeiro caractere usando o quicksort, vai ficar ainda mais rapido, mas eu aconcelho suar o metodo compareTo que compara as strings ateh achar qual eh a q vem antes…

O
import java.util.*;

public class teste {

public static void main(String[] args) {

String a[] = {Maria, Joao, Renan};

List lista = Arrays.asList(a);

Collections.sort(lista);

System.out.println(lista);

}

}

Seguindo este exemplo mais simples que ja me basta ^^ nesta parte aqui oh “String a[] = {“Maria”, “Joao”, “Renan”};” eu gostaria de nao por maria, joao … eu ja tenho Titulos de livros para por ae que apresentam em outro Array ^^ como poderia jogar ali ? vamos supor …

Livros temp = new Livros();

temp = (Livros) lista_de_livros[i];

for (int i = 0; i < 10; i++)

{

String a[] = temp.getTitulo();

}

porém nao funciona desta forma =/

J

neste seu trecho voce quer pegar os titulos e preencher na ordem o vetor a que voce esta criando??

Livros temp = new Livros&#40;&#41;;
temp = &#40;Livros&#41; lista_de_livros&#91;i&#93;;
for &#40;int i = 0; i &lt; 10; i++&#41;
&#123;
String a&#91;&#93; = temp.getTitulo&#40;&#41;;
&#125;

entao voce deveria trazer a instancia de “a” para fora do laço, pois ele esta iterando isso vai dar erro de compilacao… e colocar o indice no vetor temp para pegar o titulo e entao colocar no “a”.

String&#91;&#93; a = new String&#91;temp.length&#93;;

for&#40;;;&#41;&#123;
   a = temp&#91;i&#93;.get&#40;&#41;;
&#125;

entendeu!

M

“Felipe”:
fiz um teste agora usando inteiros em q a diferenca ficou bem evidente:

quicksort levou 33 milisegundos e bublesort levou mais de 84 segundos, uma diferenca maior q 2000x!!!

usei esse codigo pra esse teste:

OBS: alterei seu codigo para funcionar com inteiros, caso eu tenha cometido algum equivoco ou deserrumado algo sem querer me avise :wink:

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  long ms;
  int array&#91;&#93;, copia&#91;&#93; = geraArray&#40;100000&#41;;
  array = new int&#91;copia.length&#93;;
  copia&#40;array, copia&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  quicksort&#40;0, array.length - 1, array&#41;;
  System.out.println&#40;"Quicksort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
  copia&#40;array, copia&#41;;
  ms = System.currentTimeMillis&#40;&#41;;
  bubble&#40;array&#41;;
  System.out.println&#40;"Bubble&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
 &#125;
 public static void copia&#40;int array&#91;&#93;, int copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41;&#123;
   array&#91;i&#93; = copia&#91;i&#93;;
  &#125;
 &#125;
 public static int&#91;&#93; geraArray&#40;int size&#41;&#123;
  int array&#91;&#93; = new int&#91;size&#93;;
  for &#40;int i = 0; i &lt; size; i++&#41;&#123;
   array&#91;i&#93; = &#40;int&#41;&#40;Math.random&#40;&#41; * size&#41;;
  &#125;
  return array;
 &#125;
 public static void quicksort&#40;int p, int q, int array&#91;&#93;&#41;&#123;
 if &#40;p &lt; q&#41;&#123;
  int j = p - 1;
  int aux = array&#91;q&#93;;
  for &#40;int i = p; i &lt;= q; i++&#41;&#123;
   if &#40;array&#91;i&#93; &lt;= aux&#41;&#123;
    int aux2 = array&#91;i&#93;;
    array&#91;i&#93; = array&#91;++j&#93;;
    array&#91;j&#93; = aux2;
   &#125;
  &#125;
  quicksort&#40;p, j - 1, array&#41;;
  quicksort&#40;j + 1, q, array&#41;;
 &#125;
&#125; 
 public static int&#91;&#93; bubble&#40;int&#91;&#93; intArray&#41;&#123;
        int   cur = 0;
        int limit = intArray.length - 1;
        int start = 0;
        while&#40;start &lt; limit&#41; &#123;
            for&#40;cur = start; cur &lt; limit; cur++&#41; &#123;
                if&#40;intArray&#91;cur&#93; &gt; intArray&#91;cur + 1&#93;&#41; &#123;
                    int tempValue  = intArray&#91;cur&#93;;
                    intArray&#91;cur&#93;     = intArray&#91;cur + 1&#93;;
                    intArray&#91;cur + 1&#93; = tempValue;
                &#125;
            &#125;
            for&#40;cur = limit; --cur &gt;= start;&#41; &#123;
                if&#40;intArray&#91;cur&#93; &gt; intArray&#91;cur + 1&#93;&#41; &#123;
                    int tempValue = intArray&#91;cur&#93;;
                    intArray&#91;cur&#93;      = intArray&#91;cur + 1&#93;;
                    intArray&#91;cur + 1&#93;  = tempValue;
                &#125;
            &#125;
            start++;
            limit--;
        &#125;
        return intArray;
    &#125; 
&#125;

outra observacao, vc n precisa retornar o array, pois os arrays sao passados por referencia, entaum as modificacoes feitas no metodo vao afetar o array original (por isso q eh feita uma copia)…

qndo estavamos comparando strings a diferenca era pequena (e o bublesort chegava a ser mais rapido), pq alem de estarmos usando arrays muito pequenos (onde ainda assim o quicksort eh mais rapido, a nao ser claro se for um array de 1 ou 2 elementos), vc estava comparando apenas o primeiro caractere, como eu jah disse inumeras vezes, vc tb pode comparar apenas o primeiro caractere usando o quicksort, vai ficar ainda mais rapido, mas eu aconcelho suar o metodo compareTo que compara as strings ateh achar qual eh a q vem antes…

Eu ja desencanei do bubble, estou brincando com o meu proprio =]

Tive duas ideias, um vou chamar de chunk sorting e o outro sei la do que…

Organizando um array de int de 10 caracteres, o meu metodo esta 3x mais rapido que o quicksort por enquanto =]
Mas nao esta ordenando direito (bugs)…
A outra versao que pretendo fazer (o chunk sorting), nao sei por que, mas acho que ele vai usar o mesmo esquema do Shear Sort…sei la (vendo o applet deles funcionando, da impressao que o que é feito é a mesma coisa que pensei…mas acho que foi subconsciente, por que so pensei depois de ver :P)…

E sobre retornar o array, isso é verdade, MASSSSSSS

Fica muito feio algo como

String [] arr = new String[] {“abc”, “def”, “ghi”}.
sort(arr);

arr = Util.sort(arr); fica mais elegante e mais orientado a objeto, alem de ser padrao (todos os outros metodos retornariam algo…)…

E em termos de performance nao acho que faca diferenca, ja que retorna a referencia que ja tenho… :slight_smile:

F

posta ai o codigo q vc ta fazendo… agora fiquei curioso ehhehehehe e qm sabe posso te ajudar a arrumar os bugs :wink:

M

Eu já devo ter perdido umas 2 horas nele…
A idéia é meio que sei lá, como se fosse um bubble feito em pequenos pedaços, ligados por elos (mas não é esse o que chamarei de chunk hehe, o de chunk vai ser meio que por estatistica de numero, pra determinar em que lugar do array deve ir o numero e etc)…

Seria algo como

[telefone removido]

Na vertical =

9
0
2
3
1
5
7
4
6
8

Tipo, vou tentar mostrar o que deve acontecer (e no programa eu tinha comecado a imprimir na tela pra ver o que acontece…vou identar usando — aqui)

0
2
3
9 — 1
----- 5
----- 7
----- 9 — 4
----------- 6
----------- 8
----------- 9

isso vai ficar

0
2
3
1
5
7
4
6
8
9

Essa é a primeira iteração (com as sub-iteracoes)…ai vem a segunda, comecando do seguro caractere:

0
1
2
3
5 — 4
----- 5
----- 6
----- 7 — 8
----------- 9

E fica [telefone removido]

Já foi ordenada completamente na segunda iteracao, mas caso nao fosse, seria ordenado no máximo na quarta, que é quando fecharia o elo dos caracteres (tipo, o primeiro comeca do primeiro caractere, depois comeca do segundo, depois do terceiro, depois faz uma ultima rodada com o primeiro)…

É isso hehe aí esta o codigo =)

public static void bubble&#40;char &#91;&#93; chrArr&#41; &#123;
    int     cur = 0; 
    int   count = chrArr.length;
    // usado como 4 apenas pra testes, deve ser determinado automaticamente
    int divisor = 4;
    int   loops = &#40;int&#41; Math.ceil&#40;count / &#40;double&#41; divisor&#41;;
    // loop principal do pedaco
    System.out.println&#40;"Len&#58; " + count + ", " + "Loops&#58; " + loops&#41;;
    for&#40;int w = 0; w &lt; loops; w++&#41; &#123;
        int str = &#40;&#40;w + 1&#41; * divisor&#41; - 4 - &#40;1 * w&#41;;
        int end = str + 3;
        System.out.println&#40;"Loop principal&#58; " + str + " a " + end&#41;;
        // loop para comparar cada caractere do chunk
        for&#40;int x = 0; x &lt; 3; x++&#41; &#123;
            // sum = indice do caractere do chunk
            int  sum = w + x;
            // caractere sendo comparado
            char chr = chrArr&#91;sum&#93;;
            // indice atual do caractere
            int  idx = sum;
            System.out.println&#40;"\t" + sum + "," + chr&#41;;
            for&#40;int y = 0; y &lt; 3; y++&#41; &#123;
                char nxt = chrArr&#91;w + y&#93;;
                if&#40;chr &gt; nxt&#41; &#123;
                    idx = y;
                &#125;
            &#125;
            if&#40;idx != sum&#41; &#123;
                chrArr&#91;sum&#93; = chrArr&#91;idx&#93;;
                chrArr&#91;idx&#93; = chr;
            &#125;
        &#125;
    &#125;
    for&#40;int x = 0; x &lt; chrArr.length; x++&#41; &#123;
        System.out.print&#40;chrArr&#91;x&#93; + " "&#41;;
    &#125;
    System.exit&#40;0&#41;;
&#125;
F

qnto ao site da sun q falava sobre os metodos de ordenacao, eu dei uma olhada, e fiz um testezinho basico (jah aproveitei pra por o insertionsort junto no teste), pelo que eu vi lah, o quicksort deles estava diferente do q eu uso, e pior, eu testei o deles e caiu em um loop infinito (bem, pelo menos tava demorando uns 30 sec pra organizar um array de 10 elementos hehehehe), e por isso fiz o teste com o quicksort q eu uso, pelos meus testes, o quicksort eh MUITO mais rapido q o shearsort… vejam o resultado:

OBS: a JVM soh libera 64MB de memoria, por isso qndo fui usar 10000000 elementos a memoria esgotou… mas notem a GRANDE diferenca, enquanto o shearsort levou mais de 10 minutos, enquanto o quicksort n levou nem meio segundo (os outros eu “travei” pq se n iam demorar muito hehehehe, o shearsort eu ia travar depois desse, se n tivesse o problema da memoria, e veria ateh onde o quicksort vai)

bem, com esse teste vi uma coisa: o quicksort faz juz ao “quick” que leva no nome :grin:

segue o codigo (ta compridinho):

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  long ms;
  int array&#91;&#93;, copia&#91;&#93;;
  for &#40;int i = 0; i &lt; 8; i++&#41;&#123;
   copia = geraArray&#40;&#40;int&#41;Math.pow&#40;10, i&#41;&#41;;
   array = new int&#91;copia.length&#93;;
   System.out.println&#40;"NUMERO DE ELEMENTOS&#58; " + array.length&#41;;
   copia&#40;array, copia&#41;;
   if &#40;i &lt; 6&#41;&#123;
    ms = System.currentTimeMillis&#40;&#41;;
    bubblesort&#40;array&#41;;
    System.out.println&#40;"BubbleSort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
    ms = System.currentTimeMillis&#40;&#41;;
    oddevensort&#40;array&#41;;
    System.out.println&#40;"OddEvenSort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
    ms = System.currentTimeMillis&#40;&#41;;
    insertionsort&#40;array&#41;;
    System.out.println&#40;"InsertionSort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
   &#125;
   else&#123;
    System.out.println&#40;"BubbleSort&#58; um monte"&#41;;
    System.out.println&#40;"OddEvenSort&#58; um monte"&#41;;
    System.out.println&#40;"InsertionSort&#58; um monte"&#41;;
   &#125;
   if &#40;i &lt; 7&#41;&#123;
    ms = System.currentTimeMillis&#40;&#41;;
    shearsort&#40;array&#41;;
    System.out.println&#40;"ShearSort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
   &#125;
   else System.out.println&#40;"ShearSort&#58; um monte"&#41;;
   ms = System.currentTimeMillis&#40;&#41;;
   quicksort&#40;0, array.length - 1, array&#41;;
   System.out.println&#40;"QuickSort&#58; " + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
   System.out.println&#40;&#41;;
  &#125;
 &#125;
 public static void copia&#40;int array&#91;&#93;, int copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41;&#123;
   array&#91;i&#93; = copia&#91;i&#93;;
  &#125;
 &#125;
 public static int&#91;&#93; geraArray&#40;int size&#41;&#123;
  int array&#91;&#93; = new int&#91;size&#93;;
  for &#40;int i = 0; i &lt; size; i++&#41;&#123;
   array&#91;i&#93; = &#40;int&#41;&#40;Math.random&#40;&#41; * size&#41;;
  &#125;
  return array;
 &#125;
 public static void insertionsort&#40;int array&#91;&#93;&#41;&#123;
  int h, aux;
  for &#40;int i = 1; i &lt; array.length; i++&#41;&#123;
   h = i - 1;
   aux = array&#91;i&#93;;
   while &#40;h &gt;= 0 &amp;&amp; aux &lt; array&#91;h&#93;&#41;&#123;
    int aux2 = array&#91;h&#93;;
    array&#91;h&#93; = array&#91;h + 1&#93;;
    array&#91;h + 1&#93; = aux2;
    h--;
   &#125;
  &#125;
 &#125;
 static void oddevensort&#40;int a&#91;&#93;&#41;&#123;
	for &#40;int i = 0; i &lt; a.length/2; i++ &#41; &#123;
		for &#40;int j = 0; j+1 &lt; a.length; j += 2&#41; 
		    if &#40;a&#91;j&#93; &gt; a&#91;j+1&#93;&#41; &#123;
		        int T = a&#91;j&#93;;
		        a&#91;j&#93; = a&#91;j+1&#93;;
		        a&#91;j+1&#93; = T;
		    &#125;
		for &#40;int j = 1; j+1 &lt; a.length; j += 2&#41; 
		    if &#40;a&#91;j&#93; &gt; a&#91;j+1&#93;&#41; &#123;
		        int T = a&#91;j&#93;;
		        a&#91;j&#93; = a&#91;j+1&#93;;
		        a&#91;j+1&#93; = T;
		    &#125;
	&#125;	
    &#125;
 public static void quicksort&#40;int p, int q, int array&#91;&#93;&#41;&#123;
  if &#40;p &lt; q&#41;&#123;
   int j = p - 1;
   int aux = array&#91;q&#93;;
   for &#40;int i = p; i &lt;= q; i++&#41;&#123;
    if &#40;array&#91;i&#93; &lt;= aux&#41;&#123;
     int aux2 = array&#91;i&#93;;
     array&#91;i&#93; = array&#91;++j&#93;;
     array&#91;j&#93; = aux2;
    &#125;
   &#125;
   quicksort&#40;p, j - 1, array&#41;;
   quicksort&#40;j + 1, q, array&#41;;
  &#125;
 &#125; 
 public static void bubblesort&#40;int&#91;&#93; array&#41;&#123;
  for &#40;int i = array.length; --i &gt;= 0;&#41;&#123;
   for &#40;int j = 0; j &lt; i; j++&#41;&#123;
    if &#40;array&#91;j&#93; &gt; array&#91;j + 1&#93;&#41;&#123;
     int aux = array&#91;j&#93;;
     array&#91;j&#93; = array&#91;j + 1&#93;;
     array&#91;j + 1&#93; = aux;
    &#125;
   &#125;
  &#125;
 &#125;
 private static int Log, Rows, Cols;
    static void shearsort&#40;int a&#91;&#93;&#41;&#123;
	int pow=1, div=1;
	int h&#91;&#93;;

	for&#40;int i=1; i*i&lt;=a.length; i++&#41; 
	    if &#40;a.length % i == 0&#41; div = i;
	Rows = div; Cols = a.length / div;
	for&#40;Log=0; pow&lt;=Rows; Log++&#41; 
	    pow = pow * 2;

	h = new int&#91;Rows&#93;;
	for &#40;int i=0; i&lt;Rows; i++&#41;
	    h&#91;i&#93;=i*Cols;

	for &#40;int k=0; k&lt;Log; k++&#41; &#123;
	    for &#40;int j=0; j&lt;Cols/2; j++&#41; &#123;
		for &#40;int i=0; i&lt;Rows; i++&#41;
	            sortPart1&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,&#40;i%2==0?true&#58;false&#41;&#41;;
		for &#40;int i=0; i&lt;Rows; i++&#41;
	            sortPart2&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,&#40;i%2==0?true&#58;false&#41;&#41;;
	    &#125;
	    for &#40;int j=0; j&lt;Rows/2; j++&#41; &#123;
		for &#40;int i=0; i&lt;Cols; i++&#41;
	            sortPart1&#40;a,i,Rows*Cols+i,Cols,true&#41;;
		for &#40;int i=0; i&lt;Cols; i++&#41;
	            sortPart2&#40;a,i,Rows*Cols+i,Cols,true&#41;;
	    &#125;
	&#125;
	for &#40;int j=0; j&lt;Cols/2; j++&#41; &#123;
	    for &#40;int i=0; i&lt;Rows; i++&#41;
	        sortPart1&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,true&#41;;
	    for &#40;int i=0; i&lt;Rows; i++&#41;
	        sortPart2&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,true&#41;;
	&#125;
	for &#40;int i=0; i&lt;Rows; i++&#41;
	    h&#91;i&#93;=-1;
    &#125;

    private static void sortPart1&#40;int a&#91;&#93;, int Lo, int Hi, int Nx, boolean Up&#41;&#123;
	    for &#40;int j = Lo; j+Nx&lt;Hi; j+=2*Nx&#41; 
		if &#40;&#40;Up &amp;&amp; a&#91;j&#93; &gt; a&#91;j+Nx&#93;&#41; || !Up &amp;&amp; a&#91;j&#93; &lt; a&#91;j+Nx&#93;&#41; &#123;
		    int T = a&#91;j&#93;;
		    a&#91;j&#93; = a&#91;j+Nx&#93;;
		    a&#91;j+Nx&#93; = T;
		&#125;
    &#125;

    private static void sortPart2&#40;int a&#91;&#93;, int Lo, int Hi, int Nx, boolean Up&#41;&#123;
	    for &#40;int j = Lo+Nx; j+Nx&lt;Hi; j+=2*Nx&#41; 
		if &#40;&#40;Up &amp;&amp; a&#91;j&#93; &gt; a&#91;j+Nx&#93;&#41; || !Up &amp;&amp; a&#91;j&#93; &lt; a&#91;j+Nx&#93;&#41; &#123;
		    int T = a&#91;j&#93;;
		    a&#91;j&#93; = a&#91;j+Nx&#93;;
		    a&#91;j+Nx&#93; = T;
		&#125;
    &#125;
&#125;
M
"Felipe":
qnto ao site da sun q falava sobre os metodos de ordenacao, eu dei uma olhada, e fiz um testezinho basico (jah aproveitei pra por o insertionsort junto no teste), pelo que eu vi lah, o quicksort deles estava diferente do q eu uso, e pior, eu testei o deles e caiu em um loop infinito (bem, pelo menos tava demorando uns 30 sec pra organizar um array de 10 elementos hehehehe), e por isso fiz o teste com o quicksort q eu uso, pelos meus testes, o quicksort eh MUITO mais rapido q o shearsort... vejam o resultado:
NUMERO DE ELEMENTOS: 1 BubbleSort: 0 OddEvenSort: 0 InsertionSort: 0 ShearSort: 0 QuickSort: 0

NUMERO DE ELEMENTOS: 10
BubbleSort: 0
OddEvenSort: 0
InsertionSort: 0
ShearSort: 0
QuickSort: 0

NUMERO DE ELEMENTOS: 100
BubbleSort: 1
OddEvenSort: 2
InsertionSort: 0
ShearSort: 4
QuickSort: 0

NUMERO DE ELEMENTOS: 1000
BubbleSort: 7
OddEvenSort: 9
InsertionSort: 5
ShearSort: 5
QuickSort: 2

NUMERO DE ELEMENTOS: 10000
BubbleSort: 661
OddEvenSort: 630
InsertionSort: 315
ShearSort: 120
QuickSort: 3

NUMERO DE ELEMENTOS: 100000
BubbleSort: 75894
OddEvenSort: 112651
InsertionSort: 36004
ShearSort: 5892
QuickSort: 39

NUMERO DE ELEMENTOS: 1000000
BubbleSort: um monte
OddEvenSort: um monte
InsertionSort: um monte
ShearSort: 658970
QuickSort: 403

Exception in thread "main" java.lang.OutOfMemoryError

OBS: a JVM soh libera 64MB de memoria, por isso qndo fui usar 10000000 elementos a memoria esgotou... mas notem a GRANDE diferenca, enquanto o shearsort levou mais de 10 minutos, enquanto o quicksort n levou nem meio segundo (os outros eu "travei" pq se n iam demorar muito hehehehe, o shearsort eu ia travar depois desse, se n tivesse o problema da memoria, e veria ateh onde o quicksort vai)

bem, com esse teste vi uma coisa: o quicksort faz juz ao "quick" que leva no nome :grin:

segue o codigo (ta compridinho):

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  long ms;
  int array&#91;&#93;, copia&#91;&#93;;
  for &#40;int i = 0; i &lt; 8; i++&#41;&#123;
   copia = geraArray&#40;&#40;int&#41;Math.pow&#40;10, i&#41;&#41;;
   array = new int&#91;copia.length&#93;;
   System.out.println&#40;&quot;NUMERO DE ELEMENTOS&#58; &quot; + array.length&#41;;
   copia&#40;array, copia&#41;;
   if &#40;i &lt; 6&#41;&#123;
    ms = System.currentTimeMillis&#40;&#41;;
    bubblesort&#40;array&#41;;
    System.out.println&#40;&quot;BubbleSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
    ms = System.currentTimeMillis&#40;&#41;;
    oddevensort&#40;array&#41;;
    System.out.println&#40;&quot;OddEvenSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
    ms = System.currentTimeMillis&#40;&#41;;
    insertionsort&#40;array&#41;;
    System.out.println&#40;&quot;InsertionSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
   &#125;
   else&#123;
    System.out.println&#40;&quot;BubbleSort&#58; um monte&quot;&#41;;
    System.out.println&#40;&quot;OddEvenSort&#58; um monte&quot;&#41;;
    System.out.println&#40;&quot;InsertionSort&#58; um monte&quot;&#41;;
   &#125;
   if &#40;i &lt; 7&#41;&#123;
    ms = System.currentTimeMillis&#40;&#41;;
    shearsort&#40;array&#41;;
    System.out.println&#40;&quot;ShearSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
   &#125;
   else System.out.println&#40;&quot;ShearSort&#58; um monte&quot;&#41;;
   ms = System.currentTimeMillis&#40;&#41;;
   quicksort&#40;0, array.length - 1, array&#41;;
   System.out.println&#40;&quot;QuickSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
   System.out.println&#40;&#41;;
  &#125;
 &#125;
 public static void copia&#40;int array&#91;&#93;, int copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41;&#123;
   array&#91;i&#93; = copia&#91;i&#93;;
  &#125;
 &#125;
 public static int&#91;&#93; geraArray&#40;int size&#41;&#123;
  int array&#91;&#93; = new int&#91;size&#93;;
  for &#40;int i = 0; i &lt; size; i++&#41;&#123;
   array&#91;i&#93; = &#40;int&#41;&#40;Math.random&#40;&#41; * size&#41;;
  &#125;
  return array;
 &#125;
 public static void insertionsort&#40;int array&#91;&#93;&#41;&#123;
  int h, aux;
  for &#40;int i = 1; i &lt; array.length; i++&#41;&#123;
   h = i - 1;
   aux = array&#91;i&#93;;
   while &#40;h &gt;= 0 &amp;&amp; aux &lt; array&#91;h&#93;&#41;&#123;
    int aux2 = array&#91;h&#93;;
    array&#91;h&#93; = array&#91;h + 1&#93;;
    array&#91;h + 1&#93; = aux2;
    h--;
   &#125;
  &#125;
 &#125;
 static void oddevensort&#40;int a&#91;&#93;&#41;&#123;
	for &#40;int i = 0; i &lt; a.length/2; i++ &#41; &#123;
		for &#40;int j = 0; j+1 &lt; a.length; j += 2&#41; 
		    if &#40;a&#91;j&#93; &gt; a&#91;j+1&#93;&#41; &#123;
		        int T = a&#91;j&#93;;
		        a&#91;j&#93; = a&#91;j+1&#93;;
		        a&#91;j+1&#93; = T;
		    &#125;
		for &#40;int j = 1; j+1 &lt; a.length; j += 2&#41; 
		    if &#40;a&#91;j&#93; &gt; a&#91;j+1&#93;&#41; &#123;
		        int T = a&#91;j&#93;;
		        a&#91;j&#93; = a&#91;j+1&#93;;
		        a&#91;j+1&#93; = T;
		    &#125;
	&#125;	
    &#125;
 public static void quicksort&#40;int p, int q, int array&#91;&#93;&#41;&#123;
  if &#40;p &lt; q&#41;&#123;
   int j = p - 1;
   int aux = array&#91;q&#93;;
   for &#40;int i = p; i &lt;= q; i++&#41;&#123;
    if &#40;array&#91;i&#93; &lt;= aux&#41;&#123;
     int aux2 = array&#91;i&#93;;
     array&#91;i&#93; = array&#91;++j&#93;;
     array&#91;j&#93; = aux2;
    &#125;
   &#125;
   quicksort&#40;p, j - 1, array&#41;;
   quicksort&#40;j + 1, q, array&#41;;
  &#125;
 &#125; 
 public static void bubblesort&#40;int&#91;&#93; array&#41;&#123;
  for &#40;int i = array.length; --i &gt;= 0;&#41;&#123;
   for &#40;int j = 0; j &lt; i; j++&#41;&#123;
    if &#40;array&#91;j&#93; &gt; array&#91;j + 1&#93;&#41;&#123;
     int aux = array&#91;j&#93;;
     array&#91;j&#93; = array&#91;j + 1&#93;;
     array&#91;j + 1&#93; = aux;
    &#125;
   &#125;
  &#125;
 &#125;
 private static int Log, Rows, Cols;
    static void shearsort&#40;int a&#91;&#93;&#41;&#123;
	int pow=1, div=1;
	int h&#91;&#93;;

	for&#40;int i=1; i*i&lt;=a.length; i++&#41; 
	    if &#40;a.length % i == 0&#41; div = i;
	Rows = div; Cols = a.length / div;
	for&#40;Log=0; pow&lt;=Rows; Log++&#41; 
	    pow = pow * 2;

	h = new int&#91;Rows&#93;;
	for &#40;int i=0; i&lt;Rows; i++&#41;
	    h&#91;i&#93;=i*Cols;

	for &#40;int k=0; k&lt;Log; k++&#41; &#123;
	    for &#40;int j=0; j&lt;Cols/2; j++&#41; &#123;
		for &#40;int i=0; i&lt;Rows; i++&#41;
	            sortPart1&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,&#40;i%2==0?true&#58;false&#41;&#41;;
		for &#40;int i=0; i&lt;Rows; i++&#41;
	            sortPart2&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,&#40;i%2==0?true&#58;false&#41;&#41;;
	    &#125;
	    for &#40;int j=0; j&lt;Rows/2; j++&#41; &#123;
		for &#40;int i=0; i&lt;Cols; i++&#41;
	            sortPart1&#40;a,i,Rows*Cols+i,Cols,true&#41;;
		for &#40;int i=0; i&lt;Cols; i++&#41;
	            sortPart2&#40;a,i,Rows*Cols+i,Cols,true&#41;;
	    &#125;
	&#125;
	for &#40;int j=0; j&lt;Cols/2; j++&#41; &#123;
	    for &#40;int i=0; i&lt;Rows; i++&#41;
	        sortPart1&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,true&#41;;
	    for &#40;int i=0; i&lt;Rows; i++&#41;
	        sortPart2&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,true&#41;;
	&#125;
	for &#40;int i=0; i&lt;Rows; i++&#41;
	    h&#91;i&#93;=-1;
    &#125;

    private static void sortPart1&#40;int a&#91;&#93;, int Lo, int Hi, int Nx, boolean Up&#41;&#123;
	    for &#40;int j = Lo; j+Nx&lt;Hi; j+=2*Nx&#41; 
		if &#40;&#40;Up &amp;&amp; a&#91;j&#93; &gt; a&#91;j+Nx&#93;&#41; || !Up &amp;&amp; a&#91;j&#93; &lt; a&#91;j+Nx&#93;&#41; &#123;
		    int T = a&#91;j&#93;;
		    a&#91;j&#93; = a&#91;j+Nx&#93;;
		    a&#91;j+Nx&#93; = T;
		&#125;
    &#125;

    private static void sortPart2&#40;int a&#91;&#93;, int Lo, int Hi, int Nx, boolean Up&#41;&#123;
	    for &#40;int j = Lo+Nx; j+Nx&lt;Hi; j+=2*Nx&#41; 
		if &#40;&#40;Up &amp;&amp; a&#91;j&#93; &gt; a&#91;j+Nx&#93;&#41; || !Up &amp;&amp; a&#91;j&#93; &lt; a&#91;j+Nx&#93;&#41; &#123;
		    int T = a&#91;j&#93;;
		    a&#91;j&#93; = a&#91;j+Nx&#93;;
		    a&#91;j+Nx&#93; = T;
		&#125;
    &#125;
&#125;

Poe o mesmo valor em todos (ao inves de Math.random() ) e o seu quicksort esta dando stack overflow :P

M
"mavi":
"Felipe":
qnto ao site da sun q falava sobre os metodos de ordenacao, eu dei uma olhada, e fiz um testezinho basico (jah aproveitei pra por o insertionsort junto no teste), pelo que eu vi lah, o quicksort deles estava diferente do q eu uso, e pior, eu testei o deles e caiu em um loop infinito (bem, pelo menos tava demorando uns 30 sec pra organizar um array de 10 elementos hehehehe), e por isso fiz o teste com o quicksort q eu uso, pelos meus testes, o quicksort eh MUITO mais rapido q o shearsort... vejam o resultado:
NUMERO DE ELEMENTOS: 1 BubbleSort: 0 OddEvenSort: 0 InsertionSort: 0 ShearSort: 0 QuickSort: 0

NUMERO DE ELEMENTOS: 10
BubbleSort: 0
OddEvenSort: 0
InsertionSort: 0
ShearSort: 0
QuickSort: 0

NUMERO DE ELEMENTOS: 100
BubbleSort: 1
OddEvenSort: 2
InsertionSort: 0
ShearSort: 4
QuickSort: 0

NUMERO DE ELEMENTOS: 1000
BubbleSort: 7
OddEvenSort: 9
InsertionSort: 5
ShearSort: 5
QuickSort: 2

NUMERO DE ELEMENTOS: 10000
BubbleSort: 661
OddEvenSort: 630
InsertionSort: 315
ShearSort: 120
QuickSort: 3

NUMERO DE ELEMENTOS: 100000
BubbleSort: 75894
OddEvenSort: 112651
InsertionSort: 36004
ShearSort: 5892
QuickSort: 39

NUMERO DE ELEMENTOS: 1000000
BubbleSort: um monte
OddEvenSort: um monte
InsertionSort: um monte
ShearSort: 658970
QuickSort: 403

Exception in thread "main" java.lang.OutOfMemoryError

OBS: a JVM soh libera 64MB de memoria, por isso qndo fui usar 10000000 elementos a memoria esgotou... mas notem a GRANDE diferenca, enquanto o shearsort levou mais de 10 minutos, enquanto o quicksort n levou nem meio segundo (os outros eu "travei" pq se n iam demorar muito hehehehe, o shearsort eu ia travar depois desse, se n tivesse o problema da memoria, e veria ateh onde o quicksort vai)

bem, com esse teste vi uma coisa: o quicksort faz juz ao "quick" que leva no nome :grin:

segue o codigo (ta compridinho):

public class Teste&#123;
 public static void main&#40;String args&#91;&#93;&#41;&#123;
  long ms;
  int array&#91;&#93;, copia&#91;&#93;;
  for &#40;int i = 0; i &lt; 8; i++&#41;&#123;
   copia = geraArray&#40;&#40;int&#41;Math.pow&#40;10, i&#41;&#41;;
   array = new int&#91;copia.length&#93;;
   System.out.println&#40;&quot;NUMERO DE ELEMENTOS&#58; &quot; + array.length&#41;;
   copia&#40;array, copia&#41;;
   if &#40;i &lt; 6&#41;&#123;
    ms = System.currentTimeMillis&#40;&#41;;
    bubblesort&#40;array&#41;;
    System.out.println&#40;&quot;BubbleSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
    ms = System.currentTimeMillis&#40;&#41;;
    oddevensort&#40;array&#41;;
    System.out.println&#40;&quot;OddEvenSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
    ms = System.currentTimeMillis&#40;&#41;;
    insertionsort&#40;array&#41;;
    System.out.println&#40;&quot;InsertionSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
   &#125;
   else&#123;
    System.out.println&#40;&quot;BubbleSort&#58; um monte&quot;&#41;;
    System.out.println&#40;&quot;OddEvenSort&#58; um monte&quot;&#41;;
    System.out.println&#40;&quot;InsertionSort&#58; um monte&quot;&#41;;
   &#125;
   if &#40;i &lt; 7&#41;&#123;
    ms = System.currentTimeMillis&#40;&#41;;
    shearsort&#40;array&#41;;
    System.out.println&#40;&quot;ShearSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
    copia&#40;array, copia&#41;;
   &#125;
   else System.out.println&#40;&quot;ShearSort&#58; um monte&quot;&#41;;
   ms = System.currentTimeMillis&#40;&#41;;
   quicksort&#40;0, array.length - 1, array&#41;;
   System.out.println&#40;&quot;QuickSort&#58; &quot; + &#40;System.currentTimeMillis&#40;&#41; - ms&#41;&#41;;
   System.out.println&#40;&#41;;
  &#125;
 &#125;
 public static void copia&#40;int array&#91;&#93;, int copia&#91;&#93;&#41;&#123;
  for &#40;int i = 0; i &lt; array.length; i++&#41;&#123;
   array&#91;i&#93; = copia&#91;i&#93;;
  &#125;
 &#125;
 public static int&#91;&#93; geraArray&#40;int size&#41;&#123;
  int array&#91;&#93; = new int&#91;size&#93;;
  for &#40;int i = 0; i &lt; size; i++&#41;&#123;
   array&#91;i&#93; = &#40;int&#41;&#40;Math.random&#40;&#41; * size&#41;;
  &#125;
  return array;
 &#125;
 public static void insertionsort&#40;int array&#91;&#93;&#41;&#123;
  int h, aux;
  for &#40;int i = 1; i &lt; array.length; i++&#41;&#123;
   h = i - 1;
   aux = array&#91;i&#93;;
   while &#40;h &gt;= 0 &amp;&amp; aux &lt; array&#91;h&#93;&#41;&#123;
    int aux2 = array&#91;h&#93;;
    array&#91;h&#93; = array&#91;h + 1&#93;;
    array&#91;h + 1&#93; = aux2;
    h--;
   &#125;
  &#125;
 &#125;
 static void oddevensort&#40;int a&#91;&#93;&#41;&#123;
	for &#40;int i = 0; i &lt; a.length/2; i++ &#41; &#123;
		for &#40;int j = 0; j+1 &lt; a.length; j += 2&#41; 
		    if &#40;a&#91;j&#93; &gt; a&#91;j+1&#93;&#41; &#123;
		        int T = a&#91;j&#93;;
		        a&#91;j&#93; = a&#91;j+1&#93;;
		        a&#91;j+1&#93; = T;
		    &#125;
		for &#40;int j = 1; j+1 &lt; a.length; j += 2&#41; 
		    if &#40;a&#91;j&#93; &gt; a&#91;j+1&#93;&#41; &#123;
		        int T = a&#91;j&#93;;
		        a&#91;j&#93; = a&#91;j+1&#93;;
		        a&#91;j+1&#93; = T;
		    &#125;
	&#125;	
    &#125;
 public static void quicksort&#40;int p, int q, int array&#91;&#93;&#41;&#123;
  if &#40;p &lt; q&#41;&#123;
   int j = p - 1;
   int aux = array&#91;q&#93;;
   for &#40;int i = p; i &lt;= q; i++&#41;&#123;
    if &#40;array&#91;i&#93; &lt;= aux&#41;&#123;
     int aux2 = array&#91;i&#93;;
     array&#91;i&#93; = array&#91;++j&#93;;
     array&#91;j&#93; = aux2;
    &#125;
   &#125;
   quicksort&#40;p, j - 1, array&#41;;
   quicksort&#40;j + 1, q, array&#41;;
  &#125;
 &#125; 
 public static void bubblesort&#40;int&#91;&#93; array&#41;&#123;
  for &#40;int i = array.length; --i &gt;= 0;&#41;&#123;
   for &#40;int j = 0; j &lt; i; j++&#41;&#123;
    if &#40;array&#91;j&#93; &gt; array&#91;j + 1&#93;&#41;&#123;
     int aux = array&#91;j&#93;;
     array&#91;j&#93; = array&#91;j + 1&#93;;
     array&#91;j + 1&#93; = aux;
    &#125;
   &#125;
  &#125;
 &#125;
 private static int Log, Rows, Cols;
    static void shearsort&#40;int a&#91;&#93;&#41;&#123;
	int pow=1, div=1;
	int h&#91;&#93;;

	for&#40;int i=1; i*i&lt;=a.length; i++&#41; 
	    if &#40;a.length % i == 0&#41; div = i;
	Rows = div; Cols = a.length / div;
	for&#40;Log=0; pow&lt;=Rows; Log++&#41; 
	    pow = pow * 2;

	h = new int&#91;Rows&#93;;
	for &#40;int i=0; i&lt;Rows; i++&#41;
	    h&#91;i&#93;=i*Cols;

	for &#40;int k=0; k&lt;Log; k++&#41; &#123;
	    for &#40;int j=0; j&lt;Cols/2; j++&#41; &#123;
		for &#40;int i=0; i&lt;Rows; i++&#41;
	            sortPart1&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,&#40;i%2==0?true&#58;false&#41;&#41;;
		for &#40;int i=0; i&lt;Rows; i++&#41;
	            sortPart2&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,&#40;i%2==0?true&#58;false&#41;&#41;;
	    &#125;
	    for &#40;int j=0; j&lt;Rows/2; j++&#41; &#123;
		for &#40;int i=0; i&lt;Cols; i++&#41;
	            sortPart1&#40;a,i,Rows*Cols+i,Cols,true&#41;;
		for &#40;int i=0; i&lt;Cols; i++&#41;
	            sortPart2&#40;a,i,Rows*Cols+i,Cols,true&#41;;
	    &#125;
	&#125;
	for &#40;int j=0; j&lt;Cols/2; j++&#41; &#123;
	    for &#40;int i=0; i&lt;Rows; i++&#41;
	        sortPart1&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,true&#41;;
	    for &#40;int i=0; i&lt;Rows; i++&#41;
	        sortPart2&#40;a,i*Cols,&#40;i+1&#41;*Cols,1,true&#41;;
	&#125;
	for &#40;int i=0; i&lt;Rows; i++&#41;
	    h&#91;i&#93;=-1;
    &#125;

    private static void sortPart1&#40;int a&#91;&#93;, int Lo, int Hi, int Nx, boolean Up&#41;&#123;
	    for &#40;int j = Lo; j+Nx&lt;Hi; j+=2*Nx&#41; 
		if &#40;&#40;Up &amp;&amp; a&#91;j&#93; &gt; a&#91;j+Nx&#93;&#41; || !Up &amp;&amp; a&#91;j&#93; &lt; a&#91;j+Nx&#93;&#41; &#123;
		    int T = a&#91;j&#93;;
		    a&#91;j&#93; = a&#91;j+Nx&#93;;
		    a&#91;j+Nx&#93; = T;
		&#125;
    &#125;

    private static void sortPart2&#40;int a&#91;&#93;, int Lo, int Hi, int Nx, boolean Up&#41;&#123;
	    for &#40;int j = Lo+Nx; j+Nx&lt;Hi; j+=2*Nx&#41; 
		if &#40;&#40;Up &amp;&amp; a&#91;j&#93; &gt; a&#91;j+Nx&#93;&#41; || !Up &amp;&amp; a&#91;j&#93; &lt; a&#91;j+Nx&#93;&#41; &#123;
		    int T = a&#91;j&#93;;
		    a&#91;j&#93; = a&#91;j+Nx&#93;;
		    a&#91;j+Nx&#93; = T;
		&#125;
    &#125;
&#125;

Poe o mesmo valor em todos (ao inves de Math.random() ) e o seu quicksort esta dando stack overflow :P

PS: voce pode usar o System.arraycopy para copiar o array (sem ter que ficar gerando e percorrendo ele).

Criado 22 de setembro de 2004
Ultima resposta 28 de set. de 2004
Respostas 36
Participantes 7