Ordenar pelo quicksort

7 respostas
J

boa noite

peço ajuda de voces para que possa me ajudar estou tentando colocar um vetor para ordenar pelo quicksort

mas nao consigo fazer sua implementaçao o maximo que consegui foi isso
class Aluno {  
     
        private String nome;    
        private double nota;  
        
           Aluno (String nome,double nota){    
            this.nome=nome;    
            this.nota=nota;    
                
        }  
         
        public String getNome() {  
            return this.nome;  
       }    
      
        public double getNota() {  
            return this.nota;  
       }    
    }  
 
class QuickSort {
 
        public static void ordenar(int []v,int ini, int fim){
                int meio;
 
                if(ini<fim){
                        meio = partition(v,ini,fim);
                        ordenar(v,ini,meio);
                        ordenar(v,meio+1,fim);
                }
        }
 
        public static int partition(int []v, int ini, int fim){
                int pivo, topo,i;
                pivo = v[ini];
                topo = ini;
 
                for(i=ini+1;i<fim;i++){
                        if(v[i]<pivo){
                                v[topo]=v[i];
                                v[i]=v[topo+1];
                                topo++;        
                        }
                }
                v[topo]=pivo;
                return topo;
        }
}

public class orden{
    

public static void main(String[] args){
Aluno[] alunos = new Aluno[8];

alunos[0] = new Aluno("Anselmo",5.0);
alunos[1] = new Aluno("Andreia",3.0);
alunos[2] = new Aluno("Carlos",2.0);
alunos[3] = new Aluno("Pedro",4.0);
alunos[4] = new Aluno("Luis",6.0);
alunos[5] = new Aluno("Josea",1.0);
alunos[6] = new Aluno("Joseb",3.0);
alunos[7] = new Aluno("Josec",6.0);

QuickSort.ordenar(alunos,0,8);

for (int i=0;i<alunos.length;i++){
     System.out.print(alunos[i].getNome()+" ");    
     System.out.print(alunos[i].getNota());    
     System.out.println();
 }
}
}

mas da erro direto ,eu queria ordenar por nota

7 Respostas

lucasportela

QuickSort tunado:

private void quickSort() {
    long[] lista = new long[10];
    Arrays.sort(lista);
}
J

mas como seria essa mudança???

J

eu mudei e to usando o buble sort
veja o codigo

class Aluno {  
     
        private String nome;    
        private double nota;  
        
          public  Aluno (String nome,double nota){    
            this.nome=nome;    
            this.nota=nota;    
                
        }  
         
        public String getNome() {  
            return this.nome;  
       }    
      
        public double getNota() {  
            return this.nota;  
       }    
    } 

class BubbleSort {
      
    public void ordenar(Aluno v[]) {
           Aluno aux;
        for (int i = v.length; i >= 1; i--) {
            for (int j = 1; j < i; j++) {
                if (v[j - 1].getNota() > v[j].getNota()) {
                     aux = v[j];
                    v[j] = v[j - 1];
                    v[j - 1] = aux;
                }
            }
        }
    }
}
 

public class ordenacao{
public static void main(String[] args){
Aluno[] alunos = new Aluno[8];

alunos[0] = new Aluno("Anselmo",5.0);
alunos[1] = new Aluno("Andreia",3.0);
alunos[2] = new Aluno("Carlos",2.0);
alunos[3] = new Aluno("Pedro",4.0);
alunos[4] = new Aluno("Luis",6.0);
alunos[5] = new Aluno("Josea",1.0);
alunos[6] = new Aluno("Joseb",3.0);
alunos[7] = new Aluno("Josec",6.0);

BubbleSort.ordenar(alunos);


for (int i=0;i<alunos.length;i++){
     System.out.print(alunos[i].getNome()+" ");    
     System.out.print(alunos[i].getNota());    
      System.out.println();
}

}
}

so que continua dando o seguinte erro

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code - non-static method ordenar(Aluno[]) cannot be referenced from a static context
at ordenacao.main(ordenacao.java:52)
Java Result: 1

J

valeu consegui usar os algoritmos de ordençao
so que agora preciso criar um metodo que retorne a quantidade exata de elementos no array

aqui vai o codigo do que eu to falando

class Automovel {      
        private String nome;    
        private float velocidade;  
        
          public  Automovel (String nome,float velocidade){    
            this.nome=nome;    
            this.velocidade =velocidade;    
                
        }  
         
        public String getNome() {  
            return this.nome;  
       }    
      
        public float getVelocidade() {  
            return this.velocidade;  
       }    
    } 
class Contaelemento{
 public static int contador(Automovel [] v){
       int j;
        j=0;
    for(int i=0;i<v.length;i++){
           if("".equals(v[i].getNome())){
             j= j+1;// ELA NAO ACEITA A ATRIBUIÇÃO
           }
      } 
  return j;
    }
}
class BubbleSort2 {      
    public static void ordenar(Automovel v[]) {
           Automovel aux;
        for (int i = v.length; i >= 1; i--) {
            for (int j = 1; j < i; j++) {
                if (v[j - 1].getVelocidade() > v[j].getVelocidade()) {
                     aux = v[j];
                    v[j]= v[j - 1];
                    v[j - 1]= aux;
                }
            }
        }
    }
}
 
 class Selectionsort2{
    public static void ordenar(Automovel [] v) {
   int index_min;
    Automovel   aux;
 
   for (int i = 0; i < v.length; i++) {
       index_min = i;
       for (int j = i + 1; j < v.length; j++) {
          if (v[j].getVelocidade() < v[index_min].getVelocidade()) {
             index_min = j;
          }
       }
       if (index_min != i) {
         aux = v[index_min];
         v[index_min] = v[i];
         v[i] = aux;
       }
   }
}
}
class InsertionSort2{
     public static void ordenar(Automovel [] array,int tam) { 
       for (int i = 1; i < tam-1; i++)  {
           Automovel a = array[i];
            for (int j = i-1 ; j >= 0 && array[j].getVelocidade() > a.getVelocidade(); j--){
                   
                array[j + 1] = array[j];
                    array[j] = a;
                        }
                }
              
        }
}
class Mergersort2{
    
   public static void ordenar(Automovel [] vetor,int inicio, int fim) {
 
        if (inicio < fim) {
                int meio = (inicio + fim) / 2;
                ordenar(vetor,inicio, meio);
                ordenar(vetor,meio + 1, fim);
                mesclar(vetor,inicio, meio, fim);
        }
 
} 
   public static void mesclar(Automovel[] vetor,int inicio, int meio, int fim) {
 
        int tamanho = fim - inicio + 1;
 
        Automovel[] temp = new Automovel[tamanho];
 
        System.arraycopy(vetor, inicio, temp, 0, tamanho);
 
        int i = 0;
        int j = meio - inicio + 1;
         for (int posicao = 0; posicao < tamanho; posicao++) {
            if (j <= tamanho - 1) {
              if (i <= meio - inicio) {
                if (temp[i].getVelocidade() < temp[j].getVelocidade()) {
                     vetor[inicio + posicao] = temp[i++];
                       } else {
                     vetor[inicio + posicao] = temp[j++];
                                }
                        } else {
                      vetor[inicio + posicao] = temp[j++];
                        }
                         } else {
                      vetor[inicio + posicao] = temp[i++];
                          }
        }
    }
}
class Quicksort2{
public static void ordenar(Automovel[]v,int ini,int fim){
    
                int meio;
                
                if(ini<fim){
                        meio = partition(v,ini,fim);
                        ordenar(v,ini,meio);
                        ordenar(v,meio+1,fim);
                }
        }
 
public static int partition(Automovel []v, int ini, int fim){
                 Automovel pivo;
                 int  topo,i;
                 pivo = v[ini];
                 topo = ini;
 
                for(i=ini+1;i<fim;i++){
                        if(v[i].getVelocidade()<pivo.getVelocidade()){
                                v[topo]=v[i];
                                v[i]=v[topo+1];
                                topo++;        
                        }
                }
                v[topo]=pivo;
                return topo;
        }

}

public class ordenacaoautomovel{
public static void main(String[] args){
Automovel[] auto = new Automovel[20];

auto[0] = new Automovel("Xsara",210.0f);
auto[1] = new Automovel("Golf",200.0f);
auto[2] = new Automovel("Corsa",150.0f);
auto[3] = new Automovel("Corolla",205.0f);

//BubbleSort2.ordenar(auto);
//Selectionsort2.ordenar(auto);
//InsertionSort2.ordenar(auto,auto.length);
//Mergersort2.ordenar(auto, 0, auto.length-1); 
//Quicksort2.ordenar(auto,0,auto.length-1);

for (int i=0;i<4;i++){
     System.out.print(auto[i].getNome()+" ");    
     System.out.print(auto[i].getVelocidade());    
     System.out.println();
         }
int p=Contaelemento.contador(auto);
System.out.println(p);

         

     }
}

so que o a variavel j nao ta entrando dentro do laço so tarecbendo a atribuiçao

exemplo a saida

Xsara 210.0
Golf 200.0
Corsa 150.0
Corolla 205.0
0 <=VARIAVEL J
simplesmente ignora o for
eu queria contar a quantidade de elementos nao nulos no vetor para dar de referencia para os algoritmos de ordenação pois o array e de tamanho 20 mas so tem 4 elementos

WellingtonRamos

jobs:
boa noite

peço ajuda de voces para que possa me ajudar estou tentando colocar um vetor para ordenar pelo quicksort

mas nao consigo fazer sua implementaçao o maximo que consegui foi isso

mas da erro direto ,eu queria ordenar por nota


Você está cometendo um erro básico.
Teu método está esperando uma coisa e você está passando outra:

Aluno[] alunos = new Aluno[8]; // ... QuickSort.ordenar(alunos,0,8);
Uma das coisas você deve alterar.

WellingtonRamos

Há duas formas de fazer essa mudança.
1- Criar um array só com as notas dos alunos (que, aliás não é int mas double) mas perderia a referência do aluno.
2- Passar a tratar a classe Aluno e, na comparação, obter a nota para comparar.

Tente implementar e coloque as dúvidas.

WellingtonRamos

o método ordenar não é estático, logo não pode ser chamado como você chamou:
BubbleSort.ordenar(alunos);

Ou cria-se uma instancia de BubbleSort ou declara ordenar como static.

Criado 14 de agosto de 2011
Ultima resposta 16 de ago. de 2011
Respostas 7
Participantes 3