There are two answers to what you want.
- The simple answer consists of preparing the environment so that you show how to run the algorithm step by step but not implement a fully functional code Debugger. More or less like the one presented here on this page
- The tricky answer is for you to get into JVM Bugger documentation website
and try to understand how Debugger works. Or see how some simple debbuger implementation was done but I believe that’s not exactly what you’re looking for.
I recommend you use the first solution. Prepare previously each of the screens for each type of algorithm you want to run with buttons to
start and go to next step.
To run step by step an algorithm you need to deconstruct its loop and turn it into functions, for example:
Bubble Sort:
public static void bubbleSort(int[] array) {
for (int j = 1; j < array.length; j++) {
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
int tmp = array[i + 1];
array[i + 1] = array[i];
array[i] = tmp;
}
}
}
}
You first need to extract the inside so:
public static void bubbleSort(int i , int[] array) {
if (array[i] > array[i + 1]) {
int tmp = array[i + 1];
array[i + 1] = array[i];
array[i] = tmp;
}
}
Now you need to put the correct inputs for this part simulating the execution. Follow full example to give you an idea:
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class Sorter {
public static void main(String[] args) {
final int[] array = {5, 2, 4, 6, 1, 3};
final List<Integer> contextValues = new ArrayList<Integer>();
for (int j = 1; j < array.length; j++) {
for (int i = 0; i < array.length - j; i++) {
contextValues.add(i);
}
}
System.out.print("Array:");
printArray(array);
System.out.println();
//executa a cada 1 segundo um passo do bubble sort
final Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
int step = 0;
@Override
public void run() {
System.out.println("--------------");
System.out.println("Passo " + step);
bubbleInPosition(array, contextValues.get(step));
printArray(array);
if (step > contextValues.size()) {
t.cancel();
}
step++;
}
}, 0, 1000);
}
public static void printArray(int array[]) {
System.out.print("[");
for (int i : array) {
System.out.print(" " + i + " ,");
}
System.out.print("]");
}
private static void bubbleInPosition(int[] array, int i) {
if (array[i] > array[i + 1]) {
int tmp = array[i + 1];
array[i + 1] = array[i];
array[i] = tmp;
}
}
}
In place of Timer you would have called the next step button.
This would be a simple idea, but can be applied to various algorithms.
Do you want to do a debugging type? like netbeans and eclipse does?
– Edi. Gomes
Exactly @Edi. Gomes, of course not so many features... but available to the user...
– Johny