简体   繁体   English

气泡排序可视化(重新绘制错误)

[英]Bubble Sort Visualization (Repaint Error)

Thread one = new Thread(){
    public void run(){
        while(true){
            for (int m=listlen-1;m>=1;m--){
                flag=0;

                for (int n=0;n<m;n++){
                    if (a[n+1]<a[n]){
                        temp=a[n+1];
                        repaint();
                        a[n+1]=a[n];
                        repaint();
                        a[n]=temp;
                        repaint();
                        flag=1;
                    }
                }

                if (flag==0){
                    m=0;
                }
            }
            try 
            {
                Thread.sleep (100); 

            } 
            catch (InterruptedException ex) 
            {
            }
        }
    }
};
one.start();

Hello friends of Stack Overflow, I've stumbled across a problem in my code which I'm having a degree of difficulty of trying to wrap my head around. 您好,Stack Overflow的朋友们,我偶然发现了我的代码中的一个问题,该问题让我难以理解。
I'm creating a GUI that displays the objects as they're being sorted by this Bubble Sort. 我正在创建一个GUI,以显示通过气泡排序对对象进行排序的对象。 However what my code currently accomplishes is show the finished list and then it displays it, 但是我的代码当前完成的工作是显示完成的列表,然后显示它,
I believe this is a problem with my thread but I haven't been able to fix it. 我认为这是我的线程存在的问题,但我无法修复它。

You are doing the waiting ( Thread.sleep(100) ) outside of of your outer for loop, and hence after the sorting is finished. 您正在外部for循环之外进行等待( Thread.sleep(100) ),因此排序完成之后。

Instead, you should put the waiting inside the body of your for loop, or may be even before each of your repaint() calls. 相反,您应该将等待放置for循环的主体内,或者甚至可以在每个repaint()调用之前进行。

Thread one = new Thread() {
    public void run() {
        while (true) {
            for (int m = listlen - 1; m >= 1; m--) {
                flag = 0;
                    for (int n = 0; n < m; n++) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                    }
                    if (a[n + 1] < a[n]) {
                        temp = a[n + 1];
                        repaint();
                        a[n + 1] = a[n];
                        repaint();
                        a[n] = temp;
                        repaint();
                        flag = 1;
                    }
                }

                if (flag == 0) {
                    m = 0;
                }
            }
        }
    }
};
one.start();

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

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