I would like suggestions on how to implement the walkthrough feature, whether there is any standard, library, or if someone has already implemented something similar and could share the code for study.
I would like suggestions on how to implement the walkthrough feature, whether there is any standard, library, or if someone has already implemented something similar and could share the code for study.
There are two answers to what you want.
I recommend that you use the first solution. Pre-prepare each of the screens for each type of algorithm you want to run with buttons for start and go to the next step. To run an algorithm step by step you need to deconstruct your 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 have to extract the inner part like this:
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 to this part by simulating execution. Here's a complete 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 the Timer you would have to call the next step button. This would be a simple idea, but it can be applied to various algorithms.