昨天我看到一些關於比較排序算法的很酷的視頻。我決定寫同樣的內容,但剛開始後我發現這種排序可視化非常慢。與此代碼爲什麼這種排序可視化如此緩慢?
import javax.swing.*;
import java.awt.*;
class ViewSort extends JFrame implements Runnable{
private int N = 100;
private int max = 500;
private int[] array;
private Thread th;
private DrawPanel drawPanel;
long startTime;
int iter = 0;
public ViewSort(){
init();
}
private void init(){
this.setSize(N*2 + 50, max + 50);
this.setLayout(new GridLayout(1, 1));
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Stupid Sort Viewer");
drawPanel = new DrawPanel();
this.getContentPane().add(drawPanel);
array = generateArray(N, max);
th = new Thread(this);
th.start();
startTime = System.nanoTime();
}
public static int[] generateArray(int N, int max){
int[] array = new int[N];
for(int i = 0; i < N; i++){
array[i] = (int) (Math.random() * max);
}
return array;
}
@Override
public void run(){
for(int i = 0; i < N - 1; i++){
iter++;
if(array[i] > array[i + 1]){
int tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
i = 0;
}
try{
th.sleep(1);
}catch(InterruptedException ie){
ie.printStackTrace();
}
drawPanel.repaint();
}
System.out.print((System.nanoTime() - startTime)/1000/1000/1000);
System.out.print(" seconds left on ");
System.out.print(iter);
System.out.print(" iterations on sorting an array of ");
System.out.print(N);
System.out.print(" integers");
}
private void printArray(){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < N; i++){
sb.append(array[i]);
sb.append(" ");
}
System.out.println(new String(sb));
}
class DrawPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
for(int i = 0; i < N; i++){
g.fillRect(i*2 + 25, getHeight() - array[i], 2, array[i]);
}
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new ViewSort().setVisible(true);
}
});
}
}
與該代碼我有一個像上排序100點的整數
P.S.的陣列上留下116441次迭代
170秒輸出
我知道排序是最慢的(除了隨機排序),但不是這樣!
擺脫'paintChildren'方法並將邏輯放在'paintComponent'方法中。在做任何自定義繪畫之前調用'super.paintComponent' – MadProgrammer
@MadProgrammer super.paintComponent在具有哪個參數的構造函數中? – Aero
調用'super.paintComponent(g);'在'paintComponent'方法的開頭 – MadProgrammer