Ordenação de dados

Olá Galera

Estou fazendo um programa de ordenação de dados. E a cada Jbutton tenho um nome que é o método,sendo eles QuickSort ShellSort E BubbleSort.

Estou com muita dificuldade para colocar o algoritmo de cada um dentro do action Listener. Tenho o algoritmo de cada método.

public void quickSort(int v[], int esquerda, int direita) {
int vetor[] = { 109, 15, 65, 65, 76, 3, 4, 6, 8, 89 };
quickSort(vetor, 0, vetor.length - 1);
for (int i = 0; i < vetor.length; i++) {
System.out.println(" " + vetor[i]);

	int esq = esquerda;
	int dir = direita;
	int pivo = v[(esq + dir) / 2];
	int troca;
	while (esq <= dir) {
		while (v[esq] < pivo) {
			esq = esq + 1;
		}
		while (v[dir] > pivo) {
			dir = dir - 1;
		}
		if (esq <= dir) {
			troca = v[esq];
			v[esq] = v[dir];
			v[dir] = troca;
			esq = esq + 1;
			dir = dir - 1;
		}
	}
	if (dir > esquerda)
		quickSort(v, esquerda, dir);
	if (esq < direita)
		quickSort(v, esq, direita);
}
}

}

Minha tela é essa;

public PainelOrdena (){
this.setLayout(null);
this.setTitle(“Métodos de Ordenação”);
this.setBounds(200, 100, 450, 460);
this.setResizable(false);

   lbNo = new JLabel("Entrada de dados");
	lbNo.setBounds(20, 10, 395, 10);         

tentrada = new JTextField();
tentrada.setBounds(20, 30,395, 100);
            
            
            
            
jb1 = new JButton("QuickSort");

jb1.setBounds(20, 160, 95, 25);
jb1.addActionListener(new ActionListener() {

     @Override
        public void actionPerformed(ActionEvent e)  {
            try{
                
               QuickSort(); 
                System.out.println(tentrada.getText());
              
          // new QuickSort();
              
              
          /*for (int i = 0; i < vetor.length; i++) {
		System.out.println(" " + vetor[i]);
	}*/
            
            
           // public Teste(){
            //System.out.println(" " + this.vetor[1]);
            
                
               System.out.print("Deu certo Quickou");
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, "Não foi possível ");
            }
        }

                 private QuickSort[] quickSorts = new QuickSort[10];


                private void QuickSort(int v[], int esquerda, int direita) {
                    
                    
                    int vetor[] = {  };
              QuickSort(vetor, 0, vetor.length - 1);
	for (int i = 0; i < vetor.length; i++) {
		System.out.println(" " + vetor[i]);
                    
                    
                    
	int esq = esquerda;
	int dir = direita;
	int pivo = v[(esq + dir) / 2];
	int troca;
	while (esq <= dir) {
		while (v[esq] < pivo) {
			esq = esq + 1;
		}
		while (v[dir] > pivo) {
			dir = dir - 1;
		}
		if (esq <= dir) {
			troca = v[esq];
			v[esq] = v[dir];
			v[dir] = troca;
			esq = esq + 1;
			dir = dir - 1;
		}
	}
	if (dir > esquerda)
		QuickSort(v, esquerda, dir);
	if (esq < direita)
		QuickSort(v, esq, direita);

                    
                    
                    
                }

                }

                private void QuickSort() {
                   System.out.print(QuickSort.);
                }
            });









Font f1 = new Font("Arial", Font.ITALIC, 14);
	jtQui = new JTextArea();
	sp1 = new JScrollPane(jtQui);
	sp1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	sp1.setBounds(20, 225, 395, 150);
            
            
	jtQui.setEditable(false);
	jtQui.setLineWrap(true);
	jtQui.setWrapStyleWord(true);
	jtQui.setBackground(new Color(216, 216, 216));
	jtQui.setForeground(new Color(100, 0, 0));
	jtQui.setFont(f1);


jb2 = new JButton("BubbleSort");
jb2.setBounds(168, 160, 95, 25);
  jb2.addActionListener(new ActionListener() {
   
     @Override
        public void actionPerformed(ActionEvent e) {
            try{
               System.out.print("Deu certo Bublleoeuou");
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, "Não foi possível ");
            }
        }
    });

// jb2.setBounds(x,y,altura,largura);
jb3 = new JButton(“ShellSort”);
jb3.setBounds(319, 160, 95, 25);
jb3.addActionListener(new ActionListener() {

     @Override
        public void actionPerformed(ActionEvent e) {
            try{
               System.out.print("Deu certo Shellloueuou");
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, "Não foi possível ");
            }
        }
    });






this.add(lbNo);
this.add(tentrada);
this.add(jb1);
this.add(sp1);
this.add(jb2);
this.add(jb3);




addWindowListener(
		new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}

});

}
}

Me Deêm uma força,pode ver que tentei fazer um método ai em cima.

Pelo q percebi, vc tem muitos problemas de organização e indentação.
Separe o Sort, crie uma classe para isso (podem ser de outras formas):

public class Sort {

    public static void quickSort(int v[], int esquerda, int direita) {
    }

    public static void bubbleSort(int v[]) {
    }
}

na sua tela (ou em outro lugar), crie um metodo para transformar o vetor em texto:

public static String arrayToString(int v[]) {
    String result = "{";
    for (int i = 0; i < v.length; i++) {
        result = result + " " + v[i] + " ";
    }
    result = result + "}";
    return result;
}

Dessa forma poderá usar System.out.println(arrayToString(vetor)).

No action faça um teste:

jb1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)  {
        Sort.quickSort(vetor, 0, vetor.length); 
        System.out.println(arrayToString(vetor));
    }
}

Melhore a indentação e a apresentação do seu codigo no post, para facilitar a leitura e entendimento de quem lê e de outros q podem te ajudar.

Pela analise que fiz, seu código nem deveria compilar.

1 curtida

Amigo fiz o que me falou ,mas essa parte aqui não deixou compilar. Não reconhece o vetor.


Meu código do PainelOrdena;

public class PainelOrdena extends JFrame {

    public JTextArea jtQui;
    public JTextArea jtBu;
    public JTextArea jtShe;
    
  
    private JButton jb1;
    private JButton jb2;
    private JButton jb3;
    
    private JScrollPane sp1; 
    private JScrollPane sp2; 
    private JScrollPane sp3;
    
    public JTextField tentrada;
    
    private JLabel lbNo;
    
    public static String arrayToString(int v[]) {
String result = "{";
for (int i = 0; i < v.length; i++) {
    result = result + " " + v[i] + " ";
}
result = result + "}";
return result;

}

public PainelOrdena (){
this.setLayout(null);
this.setTitle(“Métodos de Ordenação”);
this.setBounds(200, 100, 450, 460);
this.setResizable(false);

   lbNo = new JLabel("Entrada de dados");
	lbNo.setBounds(20, 10, 395, 10);         

tentrada = new JTextField();
tentrada.setBounds(20, 30,395, 100);
            
            
            
            
jb1 = new JButton("QuickSort");

jb1.setBounds(20, 160, 95, 25);
jb1.addActionListener(new ActionListener() {

     @Override
       /* public void actionPerformed(ActionEvent e)  {
            try{
                
                
          
            
                
               System.out.print("Deu certo Quickou");
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, "Não foi possível ");
            }
        }*/
     public void actionPerformed(ActionEvent e)  {
    Sort.quickSort(vetor, 0, vetor.length); 
    System.out.println(arrayToString(vetor));
}

});

Font f1 = new Font("Arial", Font.ITALIC, 14);
	jtQui = new JTextArea();
	sp1 = new JScrollPane(jtQui);
	sp1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	sp1.setBounds(20, 225, 395, 150);
            
            
	jtQui.setEditable(false);
	jtQui.setLineWrap(true);
	jtQui.setWrapStyleWord(true);
	jtQui.setBackground(new Color(216, 216, 216));
	jtQui.setForeground(new Color(100, 0, 0));
	jtQui.setFont(f1);


jb2 = new JButton("BubbleSort");
jb2.setBounds(168, 160, 95, 25);
  jb2.addActionListener(new ActionListener() {
   
     @Override
        public void actionPerformed(ActionEvent e) {
            try{
               System.out.print("Deu certo Bublleoeuou");
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, "Não foi possível ");
            }
        }
    });

// jb2.setBounds(x,y,altura,largura);
jb3 = new JButton(“ShellSort”);
jb3.setBounds(319, 160, 95, 25);
jb3.addActionListener(new ActionListener() {

     @Override
        public void actionPerformed(ActionEvent e) {
            try{
               System.out.print("Deu certo Shellloueuou");
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, "Não foi possível ");
            }
        }
    });






this.add(lbNo);
this.add(tentrada);
this.add(jb1);
this.add(sp1);
this.add(jb2);
this.add(jb3);




addWindowListener(
		new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}

});

}
}

Como me falou fiz uma Classe Sort com os métodos dentro,sendo Quick,Bubble,Shell;

public class Sort {

    public static void quickSort(int v[], int esquerda, int direita) {
	int esq = esquerda;
	int dir = direita;
	int pivo = v[(esq + dir) / 2];
	int troca;
	while (esq <= dir) {
		while (v[esq] < pivo) {
			esq = esq + 1;
		}
		while (v[dir] > pivo) {
			dir = dir - 1;
		}
		if (esq <= dir) {
			troca = v[esq];
			v[esq] = v[dir];
			v[dir] = troca;
			esq = esq + 1;
			dir = dir - 1;
		}
	}
	if (dir > esquerda)
		quickSort(v, esquerda, dir);
	if (esq < direita)
		quickSort(v, esq, direita);
}
public static void main(String args[]) {
        
            //Colocar arraylist aqui no lugar desse vetor e mostrar o resultado na class main
	int vetor[] = { 100, 15, 65, 65, 76, 3, 4, 6, 8, 89 };
	quickSort(vetor, 0, vetor.length - 1);
	for (int i = 0; i < vetor.length; i++) {
		System.out.println(" " + vetor[i]);
	}
}
    
    public static void BubbleSort(String args[]){
int[] vet = {8, 9, 3, 5, 1};
int aux = 0;
int i = 0;

System.out.println("Vetor desordenado: ");
for(i = 0; i<5; i++){
	System.out.println(" "+vet[i]);
}
System.out.println(" ");

for(i = 0; i<5; i++){
	for(int j = 0; j<4; j++){
		if(vet[j] > vet[j + 1]){
			aux = vet[j];
			vet[j] = vet[j+1];
			vet[j+1] = aux;
		}
	}
}
System.out.println("Vetor organizado:");
for(i = 0; i<5; i++){
	System.out.println(" "+vet[i]);
}

}

     public static void shellSort(int a[ ])  {

for(int gap = a.length/2; gap > 0; gap=gap==2 ? 1 : (int) (gap/2.2)){
for(int i = gap; i < a.length; i++)
{
int tmp = a[i];
int j;
for(j=i;j>= gap && tmp <a[j-gap]; j-=gap)
{
a[j] = a[j-gap];
}
a[j] = tmp;
}
}

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

}

}

Amigo só me desculpe sobre como postar melhor o código aqui no post,estou estudando como faz para arrumar legal aqui…

Faltou criar o vetor, acho que deve ser criado como atributo da classe PainelOrdena

Para postar melhor o codigo:

  • pressione enter (precisa de uma linha em branco antes do código)
  • cole seu código
  • selecione somente o codigo
  • clique no botão “</>” Texto pré-formatado (Ctrl+Shift+C)
public class PainelOrdena extends JFrame {
    
   int vetor[] = {};

Amigo fiz ,porém dá erro ainda :frowning:

Agora aprendi como faz para postar o código…Valeu