Приведенный ниже код представляет собой мою реализацию быстрой сортировки. Логика работает при удалении визуальной стороны.
Код: Выделить всё
private void quickSort(int[] arr, int high) {
new Thread(() -> {
enableButton(true);
quickSortHelper(arr, 0, high);
}).start();
}
private void quickSortHelper(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSortHelper(arr, low, pi - 1);
quickSortHelper(arr, pi + 1, high);
}
}
private void qSwapHelper(int[] arr, int i, int j) {
CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(() -> {
swapBarsWithAnimation((Rectangle) mainAPane.getChildren().get(i), (Rectangle) mainAPane.getChildren().get(j), latch);
});
try {
latch.await();
} catch (Exception _) {
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private int partition(int[] arr, int low, int high) {
// choose the pivot
int pivot = arr[high];
int i = low-1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
qSwapHelper(arr, i, j);
}
}
qSwapHelper(arr, i+1, high);
return (i+1);
}
Код: Выделить всё
private void swapBarsWithAnimation(Rectangle bar1, Rectangle bar2, CountDownLatch latch) {
double bar1Pos = AnchorPane.getLeftAnchor(bar1);
double bar2Pos = AnchorPane.getLeftAnchor(bar2);
TranslateTransition bar1ToBar2Transition = new TranslateTransition(Duration.millis(DURATION_TIME), bar1);
bar1ToBar2Transition.setByX(bar2Pos - bar1Pos);
TranslateTransition bar2ToBar1Transition = new TranslateTransition(Duration.millis(DURATION_TIME), bar2);
bar2ToBar1Transition.setByX(bar1Pos - bar2Pos);
ParallelTransition pt = new ParallelTransition(bar1ToBar2Transition, bar2ToBar1Transition);
Double finalBar2Pos = bar2Pos;
Double finalBar1Pos = bar1Pos;
pt.setOnFinished(_ -> {
AnchorPane.setLeftAnchor(bar1, finalBar2Pos);
AnchorPane.setLeftAnchor(bar2, finalBar1Pos);
ObservableList children = mainAPane.getChildren();
int indexOfBar1 = children.indexOf(bar1);
int indexOfBar2 = children.indexOf(bar2);
children.removeAll(bar1, bar2);
children.add(indexOfBar1, bar2);
children.add(indexOfBar2, bar1);
bar1.setTranslateX(0);
bar2.setTranslateX(0);
latch.countDown();
});
pt.play();
}
Я думал добавить переходы в очередь или список, а затем выполнить их. , таким образом, они определенно будут работать по порядку?
Я собираюсь добавить больше видов, включая сортировку слиянием, и предполагаю, что мне придется столкнуться с той же проблемой.
Любая помощь будет очень признательна, я немного застрял.
Подробнее здесь: https://stackoverflow.com/questions/790 ... visualiser
Мобильная версия