Skip to content
Advertisement

How to update Sorting Algorithm Visualization?

I have been making a sorting algorithm visualizer in Java using Java Swing and AWT and coded insertion sort to see if it would be able to work. The algorithm works in the sense that when this program is run you can shuffle and sort the algorithm using insertion short but you don’t actually see the algorithm in action. It just happens instantly and have been looking for ways to add some sort of delay but I can’t find any sources to help me.

I set it up with 4 java classes, the main which just init’s the window, the window class, array visualizer class, and the insertion sort class.

Window.java:

JavaScript

ArrayVisualizer.java:

JavaScript

InsertionSort.java:

JavaScript

UPDATE (Here is the modified code, I added selection sort as well and heavily modified the suggestion I checkmarked):

Main.java:

JavaScript

Window.java:

JavaScript

ArrayVisualizer.java:

JavaScript

InsertionSort.java:

JavaScript

SelectionSort.java:

JavaScript

Advertisement

Answer

Call an action with a swing timer every second that will return an intermediate array. Then paint this intermediate array. Repeat until the array is sorted.

To obtain an intermediate array, modify the InsertionSort from a static method to a class method that will store the variable i so that we can resume sorting when called again.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement