简体   繁体   English

如何制作QuickSort图形?

[英]How to make QuickSort graphic?

My current code does "QuickSorting" fine however, it displays sorted on the second print of screen. 我当前的代码可以很好地执行“ QuickSorting”,但它会在屏幕的第二张屏幕上显示排序。 I want to have a better visualization of what's happening when i invoke "QuickSort", so as to have it sorted in around 5 prints of screen. 我想对调用“ QuickSort”时发生的情况有更好的可视化,以便将其分类在屏幕的5张照片中。 My code is underneath. 我的代码在下面。

1 1个

public class Frame1 extends javax.swing.JFrame {

  public Presentation() {
    initComponents();    
  }

  MyArrayClass myArrayObject = new MyArrayClass(25);

  public void BeginTimer() {
    class RemindTask extends TimerTask {                                  
      @Override            
        public void run() {                                
          paintAndSort();                
        }
    }  
    new Timer().scheduleAtFixedRate(new RemindTask(), 2000, 2000);
  }

  public void paintAndSort() {        
    int size = Integer.parseInt(txtSizeOfArray.getText());
    Graphics g = this.getGraphics();
    g.clearRect(15, 200, 270, 200);
    g.drawRect(15, 200, 270, 200);
    g.setColor(Color.DARK_GRAY);
    int x = 15;

    for (int i = 0; i < size; i++) {
       int value = myArrayObject.MyArray[i];
       g.fillRect(x, 300 - value, 9, value);
       x += 10;
    }        
    sortIt();            
  }

  Public void sortIt() {
     int size = Integer.parseInt(txtSizeOfArray.getText());
     myArrayObject.quickSort(0, size - 1);
  }
} 

2 2

public class MyArrayClass {

int myArray[];
int arraySize;    
int result;

  public MyArrayClass(int size) {
    arraySize = size;
    myArray = new int[arraySize];
  }

  public void numberGenerator() {        
     for (int i = 0; i < arraySize; i++) {
       myArray[i] = (int) (Math.random() * 99) + 1;            
     }
  }  

  public void quickSort(int left, int right) {
     if (right - left <= 0) {
       return;
     }  else {
       int pivot = myArray[right];            
       partitioning(left, right, pivot);
       int pivotValue = result;
       quickSort(left, pivotValue - 1);
       quickSort(pivotValue + 1, right);
     }
  }

  public void partitioning(int left, int right, int pivot) {
    int leftP = left - 1;
    int rightP = right;
      while (true) {
         while (leftP < right && myArray[++leftP] < pivot) {                
         }
         while (rightP > 0 && myArray[--rightP] > pivot) {                
         }
         if (rightP <= leftP) {
           swapValues(leftP, right);
           result = leftP;
           break;
         } else {
           swapValues(leftP, rightP);
           break;
         }
      }  
  }  

  private void swapValues(int leftP, int rightP) {
    int aux = myArray[leftP];
    myArray[leftP] = myArray[rightP];
    myArray[rightP] = aux;
  }
}

There are some issues with the code. 代码存在一些问题。 In general: 一般来说:

NEVER call getGraphics on a Component ! 永远不要Component上调用getGraphics

Apart from that, some minor things (don't extend JFrame, create the GUI on the EDT, and the naming conventions mentioned in the comments). 除此之外,还有一些小事情(不要扩展JFrame,在EDT上创建GUI以及注释中提到的命名约定)。

The current structure of the code does not make it really easy to connect it to a GUI component. 代码的当前结构并不十分容易将其连接到GUI组件。 You should clearly think about how this connection should be established, and at which points in time you want the component to be updated. 您应该清楚地考虑应如何建立此连接,以及在什么时间点要更新组件。

This example shows how this could basically be done. 此示例说明了如何基本完成此操作。 It is not a very nice and generic structure, but I did not want to completely re-write your MyArrayClass or generate a huge infrastructure of interfaces, timers, listeners etc. around it. 不是一个很好的通用结构,但我不想完全重写MyArrayClass或在其周围生成庞大的接口,计时器,侦听器等基础结构。 It only shows a very simple and very pragmatic approach. 它仅显示了一种非常简单且非常实用的方法。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphicalQuickSort
{
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(new BorderLayout());

        final MyArrayClass myArrayClass = new MyArrayClass(25);
        myArrayClass.NumberGenerator();
        GraphicalQuickSortPanel panel = 
            new GraphicalQuickSortPanel(myArrayClass);
        myArrayClass.graphicalQuickSortPanel = panel;

        JButton sortButton = new JButton("Sort");
        sortButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                performSorting(myArrayClass);
            }
        });
        f.getContentPane().add(sortButton, BorderLayout.NORTH);

        f.getContentPane().add(panel, BorderLayout.CENTER);
        f.setSize(400,400);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static void performSorting(final MyArrayClass myArrayClass)
    {
        Thread thread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                myArrayClass.QuickSort(0, myArrayClass.ArraySize-1);
                System.out.println("Done");
            }
        });
        thread.start();
    }
}

class GraphicalQuickSortPanel extends JPanel 
{
    private final MyArrayClass myArrayClass;

    public GraphicalQuickSortPanel(MyArrayClass myArrayClass) 
    {
          this.myArrayClass = myArrayClass;
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        int size = myArrayClass.ArraySize;
        int barWidth = getWidth() / size; 

        for (int i = 0; i < size; i++) 
        {
            int value = myArrayClass.MyArray[i];
            int x = i * barWidth;
            int y = getHeight()-value;
            g.fillRect(x+1, y, barWidth-2, value);
        }        
    }
}


class MyArrayClass {

    int MyArray[];
    int ArraySize;    
    int res;

    // This should NOT be a direct reference, but
    // a generic listener instead!
    GraphicalQuickSortPanel graphicalQuickSortPanel;
    long delayAfterSwapMS = 500;

    public MyArrayClass(int size) {
        ArraySize = size;
        MyArray = new int[ArraySize];
    }

    public void NumberGenerator() {        
        for (int i = 0; i < ArraySize; i++) {
            MyArray[i] = (int) (Math.random() * 99) + 1;            
        }
    }  

    public void QuickSort(int Left, int Right) {
        if (Right - Left <= 0) {
            return;
        }  else {
            int Pivot = MyArray[Right];            
            Partitioning(Left, Right, Pivot);
            int PivotValue = res;
            QuickSort(Left, PivotValue - 1);
            QuickSort(PivotValue + 1, Right);
        }
    }

    public void Partitioning(int Left, int Right, int Pivot) {
        int LeftP = Left - 1;
        int RightP = Right;
        while (true) {
            while (LeftP < Right && MyArray[++LeftP] < Pivot) {                
            }
            while (RightP > 0 && MyArray[--RightP] > Pivot) {                
            }
            if (RightP <= LeftP) {
                SwapValues(LeftP, Right);
                res = LeftP;
                break;
            } else {
                SwapValues(LeftP, RightP);
                break;
            }
        }  
    }  

    private void SwapValues(int LeftP, int RightP) {
        int aux = MyArray[LeftP];
        MyArray[LeftP] = MyArray[RightP];
        MyArray[RightP] = aux;

        // This should be solved differently
        try
        {
            Thread.sleep(delayAfterSwapMS);
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
        }
        graphicalQuickSortPanel.repaint();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM