-2
void bubbleSort() {
    for (int i = num - 2; i >= 0; i--) {
        for (int j = 0; j <= i; j++) {
            if (ar[j] > ar[j+1]) {
                int t = ar[j];
                ar[j] = ar[j+1];
                ar[j+1] = t;
            }
            
            try {
                Thread.sleep(SLEEP_SORT_MS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            draw();
        }
    }
}

I was making a program to visualize bubble sort using JavaFX, and Thread.sleep() did not work properly. Is it possible to make JavaFX wait for a moment?

0009laH
  • 1,960
  • 13
  • 27
Frante
  • 1
  • 1
  • Does this help? [Java, how to make a pause in JavaFX](https://stackoverflow.com/questions/43819975/java-how-to-make-a-pause-in-javafx) – Abra May 31 '22 at 04:06
  • Study and apply [Slaw’s guide to this topic](https://stackoverflow.com/a/60685975/1155209). – jewelsea May 31 '22 at 05:59

1 Answers1

1

You can't use this Thread.sleep() in this case. Your program is only using one thread, and the graphic part is refreshing it selve 60 times per second (it dependes on you computer).

You can use PauseTransition pause = new PauseTransition(Duration.seconds(0.3)); or Timeline timeline = new Timeline();

Also you can see this links:

  • I challenge you to solve this with a PauseTransition or Timeline (i.e. provide working code for a BubbleSort animation). I think you will find that tricky compared to a task that uses runLater. – jewelsea May 31 '22 at 05:54
  • 1
    @jewelsea [Here's](https://stackoverflow.com/a/62969241/2189127) an example for an insertion sort. Once you get your head around refactoring a sorting algorithm as a stateful object with a "do next step" method, it fits nicely into a `Timeline` :). – James_D May 31 '22 at 14:01
  • Yep, nice solution by James, you can use `Timeline` for this with some refactoring :-) – jewelsea May 31 '22 at 21:58