简体   繁体   中英

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.
I'm creating a GUI that displays the objects as they're being sorted by this Bubble Sort. 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.

Instead, you should put the waiting inside the body of your for loop, or may be even before each of your repaint() calls.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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