OrdenacaoGUI.java Source code

Java tutorial

Introduction

Here is the source code for OrdenacaoGUI.java

Source

import java.util.Arrays;
import java.util.Random;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author miklecio.costa
 */
public class OrdenacaoGUI extends javax.swing.JFrame {

    private int[] valoresIniciais;

    /**
     * Creates new form OrdenacaoGUI
     */
    public OrdenacaoGUI() {
        // inicializa os componentes da interface GUI
        initComponents();
        // gera os valores nao-ordenados iniciais
        gerarValoresIniciais();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jComboBoxMetodo = new javax.swing.JComboBox<>();
        jLabel2 = new javax.swing.JLabel();
        jButtonOrdenar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabelValoresIniciais = new javax.swing.JLabel();
        jLabelValoresFinais = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabelTempo = new javax.swing.JLabel();
        jButtonGerar = new javax.swing.JButton();
        jButtonComparar = new javax.swing.JButton();
        jPanelGrafico = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel5 = new javax.swing.JLabel();
        jComboBoxTamanho = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Outras Ordenaes");

        jLabel1.setText("Valores no ordenados:");

        jComboBoxMetodo.setModel(new javax.swing.DefaultComboBoxModel<>(
                new String[] { "Comb sort", "Shell sort", "Heapsort", "Radix sort", "Counting sort" }));

        jLabel2.setText("Mtodo:");

        jButtonOrdenar.setText("Ordenar");
        jButtonOrdenar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOrdenarActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Valores ordenados:");

        jLabelValoresIniciais.setText(" ");

        jLabelValoresFinais.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabelValoresFinais.setText(" ");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Tempo gasto:");

        jLabelTempo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabelTempo.setText(" ");

        jButtonGerar.setText("Gerar");
        jButtonGerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGerarActionPerformed(evt);
            }
        });

        jButtonComparar.setText("Comparar");
        jButtonComparar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCompararActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelGraficoLayout = new javax.swing.GroupLayout(jPanelGrafico);
        jPanelGrafico.setLayout(jPanelGraficoLayout);
        jPanelGraficoLayout.setHorizontalGroup(jPanelGraficoLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 0, Short.MAX_VALUE));
        jPanelGraficoLayout.setVerticalGroup(jPanelGraficoLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 382, Short.MAX_VALUE));

        jLabel5.setText("Tamanho da entrada:");

        jComboBoxTamanho.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "20", "100", "1000" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanelGrafico, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup().addGap(8, 8, 8).addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabelValoresFinais).addComponent(jLabelValoresIniciais)
                                .addComponent(jLabel3).addComponent(jLabel4).addComponent(jLabelTempo)
                                .addComponent(jLabel1)
                                .addGroup(layout.createSequentialGroup().addComponent(jLabel2).addGap(18, 18, 18)
                                        .addComponent(jComboBoxMetodo, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(37, 37, 37).addComponent(jButtonOrdenar).addGap(18, 18, 18)
                                        .addComponent(jButtonComparar))
                                .addGroup(layout.createSequentialGroup().addComponent(jLabel5).addGap(18, 18, 18)
                                        .addComponent(jComboBoxTamanho, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(37, 37, 37).addComponent(jButtonGerar)))
                                .addGap(0, 273, Short.MAX_VALUE))
                        .addComponent(jSeparator1)).addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(24, 24, 24).addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLabel5)
                        .addComponent(jComboBoxTamanho, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonGerar)).addGap(18, 18, 18).addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelValoresIniciais).addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jComboBoxMetodo, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButtonOrdenar).addComponent(jButtonComparar))
                        .addGap(18, 18, 18).addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelValoresFinais).addGap(18, 18, 18).addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelTempo).addGap(18, 18, 18)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanelGrafico, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonOrdenarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOrdenarActionPerformed
        executarOrdenacao();
    }//GEN-LAST:event_jButtonOrdenarActionPerformed

    private void jButtonGerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGerarActionPerformed
        gerarValoresIniciais();
    }//GEN-LAST:event_jButtonGerarActionPerformed

    private void jButtonCompararActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCompararActionPerformed
        // exibe o grafico comparativo dos metodos de ordenacao
        printGraph();
    }//GEN-LAST:event_jButtonCompararActionPerformed

    // metodo que executa um algoritmo de acordo com o tipo de ordenacao recebido
    private static void runSort(int[] array, int tipo) {
        switch (tipo) {
        case 0: // comb sort
            combSort.combSort(array);
            break;
        case 1: // shell sort
            shellSort.shellSort(array);
            break;
        case 2: // heapsort
            heapSort.heapSort(array);
            break;
        case 3: // radix sort
            int k = (int) Math.ceil(Math.log10(array.length));
            radixSort.radixSort(array, k);
            break;
        case 4: // counting sort
            countingSort.countingSort(array);
            break;
        }
    }

    // metodo que converte um vetor em um string com os elementos separados por virgula
    private static String arrayToString(int[] array) {
        String string = "";

        // para vetores com mais que 23 elementos, retorna apenas os 11 primeiros e os 11 ultimos, com reticencias no meio
        if (array.length > 23) {
            int[] inicio = Arrays.copyOf(array, 11);
            int[] fim = Arrays.copyOfRange(array, array.length - 11, array.length);
            string += arrayToString(inicio);
            string += ", ..., ";
            string += arrayToString(fim);
        } else {
            // para vetores menores, exibe tudo
            for (int i = 0; i < array.length; ++i) {
                string += array[i];
                if (i != array.length - 1) {
                    string += ", ";
                }
            }
        }

        return string;
    }

    // metodo que preenche os elementos de um vetor com valores aleatorios
    private static void fillRandom(int[] valores) {
        Random rand = new Random();
        for (int i = 0; i < valores.length; i++) {
            valores[i] = rand.nextInt(valores.length);
        }
    }

    private void executarOrdenacao() {
        // atualiza a label dos valores iniciais
        jLabelValoresIniciais.setText(arrayToString(valoresIniciais));

        // cria uma copia dos valores nao-ordenados para ser alterada e manter o vetor original intacto
        int[] novo = Arrays.copyOf(valoresIniciais, valoresIniciais.length);

        // executa o algoritmo de ordenacao selecionado e mede o tempo
        long tempo;
        tempo = System.nanoTime();
        runSort(novo, jComboBoxMetodo.getSelectedIndex());
        tempo = System.nanoTime() - tempo;

        // atualiza as labels de valores finais e de tempo
        jLabelValoresFinais.setText(arrayToString(novo));
        jLabelTempo.setText(String.valueOf(tempo) + " ns");
    }

    private void gerarValoresIniciais() {
        // substitui os valores iniciais nao-ordenados por novos valores aleatorios com o tamanho selecionado
        int tamanho = Integer.valueOf(jComboBoxTamanho.getSelectedItem().toString());
        valoresIniciais = new int[tamanho];
        fillRandom(valoresIniciais);

        // atualiza a label de valores iniciais
        jLabelValoresIniciais.setText(arrayToString(valoresIniciais));
    }

    // metodo que exibe um grafico comparativo dos metodos de ordenacao
    private void printGraph() {
        long tempo;

        try {

            // conjunto de dados do grafico
            XYSeriesCollection dataset = new XYSeriesCollection();

            // series de dados a serem exibidas no grafico
            int seriesSize = 5;
            XYSeries[] series = new XYSeries[seriesSize];

            // adiciona as legendas de cada serie
            String[] legendas = { "Comb", "Shell", "Heap", "Radix", "Counting" };
            for (int i = 0; i < seriesSize; ++i) {
                series[i] = new XYSeries(legendas[i]);
            }

            // executa 180 pontos no eixo de tamanho
            for (int i = 0; i < 180; ++i) {

                // o tamanho  incrementado de 1000 em 1000
                int size = (i + 1) * 1000;

                // gera um vetor de valores aleatorios com o tamanho determinado
                int[] valores = new int[size];
                fillRandom(valores);

                int[] novo;
                // executa para cada serie
                for (int j = 0; j < seriesSize; ++j) {
                    // cria uma copia dos valores gerados, para manter o vetor original intacto e igual para todos os algoritmos
                    novo = Arrays.copyOf(valores, valores.length);

                    // executa o algoritmo daquela serie e mede o tempo
                    tempo = System.nanoTime();
                    runSort(novo, j);
                    tempo = System.nanoTime() - tempo;

                    // adiciona o ponto (tamanho, tempo) na respectiva serie
                    series[j].add(size, tempo);
                }
            }

            // adiciona todas as series ao conjunto de dados do grafico
            for (int i = 0; i < seriesSize; ++i) {
                dataset.addSeries(series[i]);
            }

            // cria o grafico com parametros personalizados
            String titulo = "Comparativo das Ordenaes";
            String eixoy = "Tempo (ns)";
            String eixox = "Tamanho";
            boolean legenda = true;
            boolean tooltips = true;
            boolean urls = true;
            JFreeChart graf = ChartFactory.createXYLineChart(titulo, eixox, eixoy, dataset,
                    PlotOrientation.VERTICAL, legenda, tooltips, urls);
            ChartPanel myChartPanel = new ChartPanel(graf, true);
            myChartPanel.setSize(jPanelGrafico.getWidth(), jPanelGrafico.getHeight());
            myChartPanel.setVisible(true);
            jPanelGrafico.removeAll();
            jPanelGrafico.add(myChartPanel);
            jPanelGrafico.revalidate();
            jPanelGrafico.repaint();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OrdenacaoGUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OrdenacaoGUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OrdenacaoGUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OrdenacaoGUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OrdenacaoGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonComparar;
    private javax.swing.JButton jButtonGerar;
    private javax.swing.JButton jButtonOrdenar;
    private javax.swing.JComboBox<String> jComboBoxMetodo;
    private javax.swing.JComboBox<String> jComboBoxTamanho;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelTempo;
    private javax.swing.JLabel jLabelValoresFinais;
    private javax.swing.JLabel jLabelValoresIniciais;
    private javax.swing.JPanel jPanelGrafico;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables
}