Métodos de ordenação lendo arquivo TXT

Oi pessoal,

Estou quebrando a cabeça para fazer testes (com tempo) com os algoritmos de ordenação lendo resultados de arquivos TXT.

Na verdade estou criando 3 arquivos TXT, um ordenado crescentemente, outro decrescentemente, e outro sem ordem, todos com 1000 valores. A geração dos arquivos e sua leitura ficaram perfeitos… mas já pra implementar o algoritmo está dando trabalho.

Vou postar as classes para vocês verem como está a “bagunça”:

------ Classe que manipula os arquivos --------

package ordenacao.ftc.br;

import java.io.*;

public class ManipulaArquivo {

public ManipulaArquivo() {
}

//Método para realizar leitura do arquivo
public void lerArq(String arq) throws Exception {
	try {
		FileReader arquivo = new FileReader(arq);
		BufferedReader leitor = new BufferedReader(arquivo);

		String linha = null;
		 while( (linha = leitor.readLine() ) != null ) {
			System.out.println(linha);
		}
		leitor.close();
		arquivo.close();

	} catch (Exception e) {
		e.printStackTrace();
	}
}

public void limpaArq(String arq) throws Exception {
	try {
		FileWriter arquivo = new FileWriter(arq);
		PrintWriter escritor = new PrintWriter(arquivo);
		
		String zera = "";
		escritor.println(zera);
		
		escritor.close();
		arquivo.close();
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}

//Método para gerar arquivo em ordem crescente
public void gArqCres(String arq, int qt) throws Exception {
	try {
		FileWriter arquivo = new FileWriter(arq);
		PrintWriter escritor = new PrintWriter(arquivo);

		for (int i = 1; i <= qt; i++)
			escritor.println(i);

		escritor.close();
		arquivo.close();

	} catch (Exception e) {
		e.printStackTrace();
	}
}

//Método para gerar arquivo descrescente
public void gArqDecr(String arq, int qt) throws Exception {
	try {
		FileWriter arquivo = new FileWriter(arq);
		PrintWriter escritor = new PrintWriter(arquivo);

		for (int i = qt; i >= 1; i--)
			escritor.println(i);

		escritor.close();
		arquivo.close();

	} catch (Exception e) {
		e.printStackTrace();
	}
}

//Método para gerar arquivo sem ordem
public void gArqSemOr(String arq, int qt) throws Exception {
	try {
		FileWriter arquivo = new FileWriter(arq);
		PrintWriter escritor = new PrintWriter(arquivo);

		int n = 0;
		for (int i = 1; i <= qt; i++)
			escritor.println((int)(java.lang.Math.random() * qt));

		escritor.close();
		arquivo.close();

	} catch (Exception e) {
		e.printStackTrace();
	}
}

}

------ Classe que manipula o tempo para contagem --------
package ordenacao.ftc.br;

import java.util.*;

public class ManipulaTempo {

public ManipulaTempo() {
}

public long getTempo() {
	GregorianCalendar data = new GregorianCalendar();
	return data.getTimeInMillis();
}

public long calcTempo(long fim, long inicio) {
	return fim - inicio;
}

}

------- Classe principal (a interface) ------------

package ordenacao.ftc.br;

import java.awt.;
import java.awt.event.
;
import java.io.File;
import java.text.*;

import javax.swing.*;

public class Principal extends JFrame {
private GridBagConstraints constantes;
private GridBagLayout layoutGB;

private JPanel painel1, painel2, painel3;

private JButton botao1, botao2;

private JLabel aviso1, aviso2, tit_alg;

private JLabel rotulo1, rotulo2, rotulo3;
private JRadioButton rb1, rb2, rb3;
private ButtonGroup rbGrupo;	

private JTextField text1, text2, text3;


public Principal() {
	super ("Teste de Desempenho de Algoritmos de Ordenação");
	
	//Zera arquivos para iniciar o programa
	ManipulaArquivo marq = new ManipulaArquivo();
	try {
		marq.limpaArq("cres.txt");
		marq.limpaArq("decr.txt");
		marq.limpaArq("semo.txt");
	} catch (Exception ex) {
		System.out.println("Erro ao manipular os arquivos.");
	}
	
	Container container = getContentPane();
	BorderLayout layout = new BorderLayout();
	container.setLayout(layout);
	
	constantes = new GridBagConstraints();
	layoutGB = new GridBagLayout();

	painel1 = new JPanel();
	painel2 = new JPanel();
	painel3 = new JPanel();
	
	//Instancia classe para manipular cliques do botão
	BotaoArquivos botArq = new BotaoArquivos();
	BotaoTestar botTes = new BotaoTestar();
	
	//Adiciona os painéis na janela
	add(painel1, BorderLayout.NORTH);
	add(painel2, BorderLayout.CENTER);
	add(painel3, BorderLayout.SOUTH);		
	
	// Seta configurações da janela
	setResizable(false);
	setSize(450, 330);
	setLocation(130, 100);
	setVisible(true);

	//Configurações do painel 1
	painel1.setBorder(BorderFactory.createTitledBorder("Arquivos"));
	painel1.setPreferredSize(new Dimension(450, 70));
	painel1.setLayout(layoutGB);
	
	//Componentes do painel 1
	botao1 = new JButton("GERAR ARQUIVOS PARA TESTE");
	botao1.addActionListener(botArq);

	aviso1 = new JLabel("ARQUIVOS PRONTOS PARA O TESTE");
	aviso1.setFont(new Font("Verdana", 0, 18));
	aviso1.setForeground(Color.RED);
	aviso1.setVisible(false);

	//Adiciona os componentes do painel 1
	addComponente(painel1, botao1, 0, 0, 1, 1);
	addComponente(painel1, aviso1, 1, 0, 1, 1);
	
	//Configurações do painel 2
	painel2.setBorder(BorderFactory.createTitledBorder("Algoritmos"));
	painel2.setLayout(layoutGB);
	
	//Componentes do painel 2
	tit_alg = new JLabel("  Escolha o algoritmo de ordenação:");
	tit_alg.setFont(new Font("Verdana", 3, 16));
		
	rb1 = new JRadioButton("Shell Sort");
	rb1.setSelected(true);
	rb2 = new JRadioButton("Quick Sort");
	rb3 = new JRadioButton("Bubble Sort");
		
	rbGrupo = new ButtonGroup();
	rbGrupo.add(rb1);
	rbGrupo.add(rb2);
	rbGrupo.add(rb3);

	//Adiciona os componentes do painel 2
	constantes.anchor = GridBagConstraints.NORTHWEST;
	constantes.weightx = 1;  
	constantes.weighty = 1;  
	addComponente(painel2, tit_alg, 0, 0, 1, 2);

	constantes.anchor = GridBagConstraints.SOUTH;
	constantes.weightx = 0;  
	constantes.weighty = 0;
	addComponente(painel2, rb1, 1, 0, 1, 1);
	addComponente(painel2, rb2, 1, 1, 1, 1);
	addComponente(painel2, rb3, 1, 2, 1, 1);

	//Configurações do painel 3
	painel3.setBorder(BorderFactory.createTitledBorder("Resultado"));
	painel3.setLayout(layoutGB);
	
	//Componentes do painel 3
	botao2 = new JButton("Iniciar teste");
	botao2.addActionListener(botTes);
	
	aviso2 = new JLabel("PRECISA GERAR OS ARQUIVOS");
	aviso2.setFont(new Font("Verdana", 1, 12));
	aviso2.setForeground(Color.RED);
		if ((new File("cres.txt") == null) && (new File("decr.txt") == null)
			&& (new File("semo.txt").length() == 0)) {
			aviso2.setVisible(false);
			botao2.setEnabled(true);
		} else {
			aviso2.setVisible(true);
			botao2.setEnabled(false);
		}
	
	rotulo1 = new JLabel("Crescente");
	rotulo1.setFont(new Font("Verdana", 1, 12));
	
	rotulo2 = new JLabel("Decrescente");
	rotulo2.setFont(new Font("Verdana", 1, 12));
	
	rotulo3 = new JLabel("Sem ordem");
	rotulo3.setFont(new Font("Verdana", 1, 12));
	
	text1 = new JTextField();
	text1.setPreferredSize(new Dimension(120,80));
	text1.setEnabled(false);
	text1.setText("00:000");
	text1.setFont(new Font("Verdana", 1, 22));
	
	text2 = new JTextField();
	text2.setPreferredSize(new Dimension(120,80));
	text2.setEnabled(false);
	text2.setText("00:000");
	text2.setFont(new Font("Verdana", 1, 22));
	
	text3 = new JTextField();
	text3.setPreferredSize(new Dimension(120,80));
	text3.setEnabled(false);
	text3.setText("00:000");
	text3.setFont(new Font("Verdana", 1, 22));
		
	//Adiciona os componentes do painel 3
	addComponente(painel3, botao2, 0, 0, 1, 1);
	addComponente(painel3, aviso2, 0, 1, 1, 2);	
	addComponente(painel3, rotulo1, 1, 0, 1, 1);
	addComponente(painel3, rotulo2, 1, 1, 1, 1);
	addComponente(painel3, rotulo3, 1, 2, 1, 1);
	addComponente(painel3, text1, 2, 0, 1, 1);
	addComponente(painel3, text2, 2, 1, 1, 1);
	addComponente(painel3, text3, 2, 2, 1, 1);
	
}


private class BotaoArquivos implements ActionListener{
	public void actionPerformed( ActionEvent e ) {
		if (e.getActionCommand() == "GERAR ARQUIVOS PARA TESTE") {
			ManipulaArquivo marq = new ManipulaArquivo();
			try {
				marq.gArqCres("cres.txt", 1000);
				marq.gArqDecr("decr.txt", 1000);
				marq.gArqSemOr("semo.txt", 1000);

				aviso1.setVisible(true);
				botao2.setEnabled(true);
				aviso2.setVisible(false);

			} catch (Exception ex) {
				System.out.println("Erro ao tentar gerar os arquivos.");
			}
		}
	}
}

private class BotaoTestar implements ActionListener{
	public void actionPerformed( ActionEvent e ) {
		if (e.getActionCommand() == "Iniciar teste") {
			ManipulaArquivo marq = new ManipulaArquivo();
			ManipulaTempo mtem = new ManipulaTempo();
			try {
				//Processa arquivo crescente
				long ini = mtem.getTempo();
				marq.lerArq("cres.txt");
				long fim = mtem.getTempo();
				
				long milis = mtem.calcTempo(fim, ini);
				if (milis > 999) {
					long seg = milis/1000;
					long mil = milis%1000;
					text1.setText(seg + ":" + mil);
				} else
					text1.setText("00:" + milis);
					
				//Processa arquivo decrescente
				long ini2 = mtem.getTempo();
				marq.lerArq("decr.txt");
				long fim2 = mtem.getTempo();
				
				long milis2 = mtem.calcTempo(fim2, ini2); 
				if (milis2 > 1000) {
					long seg2 = milis2/1000;
					long mil2 = milis2%1000;
					text2.setText(seg2 + ":" + mil2);
				} else
					text2.setText("00:" + milis2);
				
				//Processa arquivo sem ordem
				long ini3 = mtem.getTempo();
				marq.lerArq("semo.txt");
				long fim3 = mtem.getTempo();
				
				long milis3 = mtem.calcTempo(fim3, ini3);
				if (milis3 > 1000) {
					long seg3 = milis3/1000;
					long mil3 = milis3%1000;
					text3.setText(seg3 + ":" + mil3);
				} else
					text3.setText("00:" + milis3);
				
				marq.limpaArq("cres.txt");
				marq.limpaArq("decr.txt");
				marq.limpaArq("semo.txt");
				
				aviso1.setVisible(false);
				botao2.setEnabled(false);
				aviso2.setVisible(true);
			} catch (Exception ex) {
				System.out.println("Erro ao tentar limpar arquivos.");
			}
		}
	}
}

//Método para auxiliar na colocação dos componentes nos layouts GridBagLayouts
public void addComponente (JPanel painel, Component comp, int linha, int coluna,
		int altura, int largura) {
	
	constantes.gridx = coluna;
	constantes.gridy = linha;
	
	constantes.gridwidth = largura;
	constantes.gridheight = altura;
	
	layoutGB.setConstraints(comp, constantes);
	painel.add(comp);
}

public static void main(String[] args) {
	Principal p = new Principal();
	p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

------- Código do método de ordenação shell sort -----------------

private static void shellSort ( int [ ] v )
{
int i , j , h = 1, value ;

     do { h = 3 * h + 1; } while ( h < v.length );
     do {
        h /= 3;
        for ( i = h; i < v.length; i++) {
           value = v [ i ];
           j = i - h;
           while (j >= 0 && value < v [ j ])
           {
              v [ j + h ] = v [ j ];
              j -= h;
           }
           v [ j + h ] = value;
        }
  } while ( h > 1 );

}

------------------------------------------------------------------------

Preciso implementar esse algoritmo mas não estou conseguindo… se eu conseguir fazer esse, os demais conseguirei também.

Obrigado pelo apoio de vcs!

Cleber

Pensando melhor, estou postando os arquivos.java para melhor visualização do problema.

Muito obrigado a todos!

Clebet

Quer ordernar de uma maneira “feia”, mas fácil? Aprenda usar a TreeMap, aí conseguirás a chave com order crescente, para decrescer é só inverter né?
Para numa ordem aleatória, use a HashMap e “randomize” os valores na hora de inserir.

Até!