如何可视化排序算法?

时间:2018-12-24 17:07:05

标签: java algorithm swing sorting event-dispatch-thread

我想使用不同的算法对这些彩色条进行排序。

Image1

我创建了一个JFrame,并添加了八个按钮和一个JPanel。在面板中,我创建了一个数组的条形图。我想通过使用不同的排序算法(如气泡排序,选择排序,合并排序等)通过单击按钮并显示每个算法和步骤来直观地对此条形图进行排序。但是我在可视化这些算法时发现了麻烦。

这是我的代码:

public class VisuofSortTech { 
//Declarations....
private final JLabel lbl = new JLabel();
private JTextField jtf = new JTextField(10);
private JPanel pnl = new JPanel();

private final JButton bbl= new JButton("Bubble Sort");
private final JButton ins= new JButton("Insertion Sort");
private final JButton mrg= new JButton("Merge Sort");
private final JButton slc= new JButton("Selection Sort");
private final JButton qck= new JButton("Quick Sort");
private final JButton rdx= new JButton("Radix Sort");
private final JButton heap= new JButton("Heap Sort");
private final JButton stp= new JButton("Stupid Sort");
private final JButton go = new JButton("Create");

String[] parts;
int[] arr1;
BarChart chart = new BarChart();
Random rand = new Random();

//Main method....
public static void main(String[] args) {
    VisuofSortTech visuOfSortTech = new VisuofSortTech();
    System.out.println("Visual :" + visuOfSortTech);

}


// Bars
public class BarChart extends Canvas
        {
            private final Map<Color, Integer> bars =
            new LinkedHashMap<>();

        public void addBar(Color color, int value)
            {
                bars.put(color, value);
                repaint();
            }
       //
        @Override
        public void paint(Graphics g)
        {
        // determine longest bar
            int max = Integer.MIN_VALUE;
            for (int value : bars.values())
            {
                max = Math.max(max, value);
            }        

        // paint bars
        int width = (getWidth() / bars.size()) - 2;
        int x = 1;
        for (Color color : bars.keySet())
        {
            int value = bars.get(color);
            int height = (int) ((getHeight()-5) * ((double)value / max));
            g.setColor(color);
            g.fill3DRect(x, getHeight() - height, width, height , true);
            g.setColor(Color.white);
            g.drawRect(x, getHeight() - height, width, height);

            x += (width + 2);
        }
        }   

}

// Constructor........
public VisuofSortTech(){
    JFrame frame = new JFrame("DSA Project");
    frame.getContentPane().setLayout(null);

    // Label
    lbl.setText("Visualization of Sorting Algorithms");
    lbl.setFont(new Font("SansSerif", 3, 36));
    lbl.setForeground(Color.red);
    lbl.setBackground(new Color(150,235,210,100));
    lbl.setFocusable(true);
    lbl.setBounds(10,10, 620, 60);
    lbl.setMinimumSize(new Dimension(200,200));
    lbl.setOpaque(true);
    lbl.setBorder(BorderFactory.createLineBorder(Color.white, 3, true));
    frame.add(lbl);


    // Buttons
    bbl.setBounds(50, 100, 115, 35);
    bbl.setForeground(Color.magenta);
    bbl.setBackground(Color.white);
    bbl.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    bbl.setBorderPainted(true);
    frame.add(bbl);


    ins.setBounds(50, 150, 115, 35);
    ins.setForeground(Color.magenta);
    ins.setBackground(Color.white);
    ins.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    ins.setBorderPainted(true);
    frame.add(ins);


    mrg.setBounds(50, 200, 115, 35);
    mrg.setForeground(Color.magenta);
    mrg.setBackground(Color.white);
    mrg.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    mrg.setBorderPainted(true);
    frame.add(mrg);


    qck.setBounds(50, 250, 115, 35);
    qck.setForeground(Color.magenta);
    qck.setBackground(Color.white);
    qck.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    qck.setBorderPainted(true);
    frame.add(qck);


    slc.setBounds(50, 300, 115, 35);
    slc.setForeground(Color.magenta);
    slc.setBackground(Color.white);
    slc.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    slc.setBorderPainted(true);
    frame.add(slc);


    rdx.setBounds(50, 350, 115, 35);
    rdx.setForeground(Color.magenta);
    rdx.setBackground(Color.white);
    rdx.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    rdx.setBorderPainted(true);
    frame.add(rdx);


    heap.setBounds(50, 400, 115, 35);
    heap.setForeground(Color.magenta);
    heap.setBackground(Color.white);
    heap.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    heap.setBorderPainted(true);
    frame.add(heap);


    stp.setBounds(50, 450, 115, 35);
    stp.setForeground(Color.magenta);
    stp.setBackground(Color.white);
    stp.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    stp.setBorderPainted(true);
    frame.add(stp);


    go.setBounds(755, 600, 100, 30);
    go.setForeground(Color.magenta);
    go.setBackground(Color.white);
    go.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    go.setBorderPainted(true);
    frame.add(go);


    // Textfield

    jtf.setBounds(550, 600, 200, 30);
    jtf.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2, true));
    frame.add(jtf);



    // Panel

    pnl.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.white, 4, true), "Sorting Pane"));
    pnl.setBounds(342, 100, 682, 384);
    pnl.setLayout(new BorderLayout());
    pnl.setBackground(new Color(255,255,255,150));
    frame.add(pnl);


    // Color arrays
    int l= 20;
    int[] clr1= new int[l];
    int[] clr2= new int[l];
    int[] clr3= new int[l];

    // red color
    for(int i=0; i < l ;i++){
        int r= rand.nextInt(255);
        clr1[i]= r;
    }

    // green color
    for(int i=0; i < l ;i++){
        int g= rand.nextInt(255);
        clr2[i]= g;
    }

    // blue color
    for(int i=0; i < l ;i++){
        int b= rand.nextInt(255);
        clr3[i]= b;
    }

    // Array
    go.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt){
            pnl.setVisible(false);
            String str = jtf.getText();
            parts = str.split(",");
            arr1 =new int[parts.length];

            for(int i=0 ; i<parts.length; i++){
                arr1[i]=Integer.parseInt(parts[i]);
            }



    for(int i=0; i <arr1.length; i++){
    chart.addBar(new Color(clr1[i] , clr2[i] ,clr3[i]) ,arr1[i]);
    }
    pnl.add(chart);
    pnl.setVisible(true);
        }
    });


    // Bubble sort
    bbl.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt)  {
            pnl.remove(chart);
            pnl.setVisible(false);
            //Thread t = new Thread();
           int loop=arr1.length-1;
        for(int i=0; i<loop; i++){
            for(int j=0; j<loop-i;j++)
            {
                boolean exp = arr1[j]>arr1[j+1];
                if(exp)
                {
                    int temp=arr1[j];
                    arr1[j]=arr1[j+1];
                    arr1[j+1]=temp;
                    System.out.print(exp + ",");

                try{
                    Thread.sleep(250);
                }
                catch(Exception e){
                    System.out.println("Thread is not working " + e);

                }
                System.out.print(temp + ",");
                }
            }
        }
        for(int i=0; i <arr1.length; i++){
            chart.addBar(new Color(clr1[i] , clr2[i] ,clr3[i]) ,arr1[i]);
        }

        pnl.add(chart);
        pnl.setVisible(true);

    }
});


    // Frame
    Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(new Color(167,167,247));
    frame.setPreferredSize(new Dimension(screensize.width,screensize.height));
    frame.pack();
    frame.setResizable(true);
    frame.setVisible(true);

}   
}

1 个答案:

答案 0 :(得分:2)

您不能在Swing的事件调度线程中使用Thread.sleep()。但这不会减慢程序的运行速度,让您查看发生了什么。相反,它阻止了UI对包括重绘请求在内的任何内容做出响应,因此什么也没有发生,并且浪费了时间,没有任何好处。

使用Swing Timer或(更好)SwingWorker进行分步排序,并publish()将部分间的排序结果显示出来。