【问题标题】:Animation of Quick Sort Algorithm快速排序算法动画
【发布时间】:2016-05-01 01:13:05
【问题描述】:

我正在尝试使用 JavaFX 库为快速排序算法的分区部分设置动画。我把程序的所有图形部分都搞定了,但是我的步骤方法有问题。我的 step 方法存在逻辑错误,我似乎无法弄清楚它是什么。 step 方法应该在每次点击 step 按钮时执行一个 step。

private void quickSort(int lowerIndex, int higherIndex) {

    int i = lowerIndex;
    int j = higherIndex;
    // calculate pivot number, I am taking pivot as middle index number
    int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
    // Divide into two arrays
    while (i <= j) {
        /**
         * In each iteration, we will identify a number from left side which
         * is greater then the pivot value, and also we will identify a number
         * from right side which is less then the pivot value. Once the search
         * is done, then we exchange both numbers.
         */
        while (array[i] < pivot) {
            i++;
        }
        while (array[j] > pivot) {
            j--;
        }
        if (i <= j) {
            exchangeNumbers(i, j);
            //move index to next position on both sides
            i++;
            j--;
        }
    }
    // call quickSort() method recursively
    if (lowerIndex < j)
        quickSort(lowerIndex, j);
    if (i < higherIndex)
        quickSort(i, higherIndex);
}

上面的代码是快速排序算法的源代码,step方法应该只是快速排序算法的一步。我试图在 step 方法中实现相同的逻辑,但我的逻辑是错误的。该程序的正确输出在此链接http://www.cs.armstrong.edu/liang/animation/web/QuickSortPartition.html 以供参考。

下面是我正在使用的代码

 import java.util.Arrays;
 import javafx.application.Application;
 import javafx.geometry.Pos;
 import javafx.scene.Scene;
 import javafx.scene.control.Button;
 import javafx.scene.layout.BorderPane;
 import javafx.scene.layout.HBox;
 import javafx.scene.layout.Pane;
 import javafx.scene.paint.Color;
 import javafx.scene.shape.Line;
 import javafx.scene.shape.Rectangle;
 import javafx.scene.text.Text;
 import javafx.stage.Stage;

 public class AnimateQuickSort extends Application {
    public final static int ARRAY_SIZE = 20;
    private int[] array = new int[ARRAY_SIZE];
    private int leftP = 1;
    private int rightP = array.length - 1;
    private int pivot = 0;

public void start(Stage primaryStage) {
    AnimationPane pane = new AnimationPane();

    Button btStep = new Button("Step");
    Button btReset = new Button("Reset");

    HBox hBox = new HBox(5);
    hBox.getChildren().addAll(btStep, btReset);
    hBox.setAlignment(Pos.CENTER);

    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(pane);
    borderPane.setBottom(hBox);

    // Create a scene and place it in the stage
    Scene scene = new Scene(borderPane, 700, 225);
    primaryStage.setTitle("QuickSort");
    primaryStage.setScene(scene);
    primaryStage.show();

    initializeArray();

    pane.repaint();

    btStep.setOnAction(e -> {
        if (step()) {
            pane.repaint();
        } else {
            pane.repaint();
        }
    });

    btReset.setOnAction(e -> {
        reset();
        pane.repaint();
    });
}

public static void main(String[] args) {
    launch(args);
}

public void initializeArray() {

    for (int i = 0; i < array.length; i++) {
        array[i] = (int) (Math.random() * 999 + 1);
    }

    // Arrays.sort(array);

}

public void reset() {
    leftP = 1;
    rightP = array.length - 1;
    pivot = 0;
    initializeArray();
}

public boolean step() {
    // quicksort(array);
    int begin = 0;
    int pivotVal = array[0];
    int array1;

    if (leftP <= rightP && array[leftP] <= pivotVal) {
        leftP++;
        array1 = array[leftP];
        array[leftP] = array[rightP];
        array[rightP] = array1;
    }

    if (rightP >= leftP && array[rightP] > pivotVal) {
        rightP--;
    }
    if (rightP > leftP) {
        if (rightP != begin) {
            array1 = array[rightP];
            array[rightP] = array[begin];
            array[begin] = array1;
        }
    }
    // Return the index of the pivot element.
    return true;
}

class AnimationPane extends Pane {
    private int startingX = 20;
    private int startingY = 20;
    private int boxWidth = 30;
    private int boxHeight = 20;

    protected void repaint() {
        this.getChildren().clear();

        int x = startingX + 10;
        int y = startingY + 40;

        // Display array
        x = startingX + 10;
        getChildren().add(new Text(x - 15, y + 55, "Array "));
        x += 20;
        getChildren().add(new Text(x + pivot * boxWidth, y + 120, "Pivot"));
        drawArrowLine(x + 15 + pivot * boxWidth, y + 100, x + 15 + pivot * boxWidth, y + 40 + boxHeight);

        getChildren().add(new Text(x - 14 + leftP * boxWidth, startingY, "Left Pointer"));
        drawArrowLine(x + 15 + leftP * boxWidth, startingY, x + 15 + leftP * boxWidth, y + 40);

        getChildren().add(new Text(x - 14 + rightP * boxWidth, startingY, "Right Pointer"));
        drawArrowLine(x + 15 + rightP * boxWidth, startingY, x + 15 + rightP * boxWidth, y + 40);

        for (int k = 0; k < array.length; k++) {
            Rectangle rectangle = new Rectangle(x, y + 40, boxWidth, boxHeight);
            rectangle.setFill(Color.WHITE);
            rectangle.setStroke(Color.BLACK);
            getChildren().add(rectangle);
            if (array[k] != 0) {
                getChildren().add(new Text(x + 5, y + 55, array[k] + ""));
            }
            x = x + boxWidth;
        }
    }

    public void drawArrowLine(double x1, double y1, double x2, double y2) {
        getChildren().add(new Line(x1, y1, x2, y2));

        // find slope of this line
        double slope = ((((double) y1) - (double) y2)) / (((double) x1) - (((double) x2)));

        double arctan = Math.atan(slope);

        // This will flip the arrow 45 off of a
        // perpendicular line at pt x2
        double set45 = 1.57 / 2;

        // arrows should always point towards i, not i+1
        if (x1 < x2) {
            // add 90 degrees to arrow lines
            set45 = -1.57 * 1.5;
        }

        // set length of arrows
        int arrlen = 15;

        // draw arrows on line
        getChildren().add(new Line(x2, y2, (x2 + (Math.cos(arctan + set45) * arrlen)),
                ((y2)) + (Math.sin(arctan + set45) * arrlen)));

        getChildren().add(new Line(x2, y2, (x2 + (Math.cos(arctan - set45) * arrlen)),
                ((y2)) + (Math.sin(arctan - set45) * arrlen)));
    }
}
 }

【问题讨论】:

    标签: java arrays javafx logic quicksort


    【解决方案1】:

    如果没有协程,就无法单步执行递归函数(Java 中有多个协程库,但其中大多数会调整 JVM 或字节码,因此不是真正的标准东西)。

    你基本上有两种选择:

    • 如果可以的话,反转职责:代替动画调用 QuickSort 的单步,让 QuickSort 调用动画重绘。

    • 或者,为了实现一个执行单步快速排序的函数,您需要展开递归,这将要求您使用显式堆栈跟踪“深度” -对。堆栈以“整个数组”开头;在函数的顶部,您弹出一个状态并对该范围进行排序;当您递归时,您将较小的范围推入堆栈;当堆栈为空时,您就完成了。

    【讨论】:

    • 我需要展开递归但我需要不使用堆栈来完成,必须有更简单的方法。
    【解决方案2】:

    “hacky”解决方案

    这需要访问com.sun.javafx.tk.Toolkit,这不是特别好的做法,因为它位于com.sun 包中(请参阅It is a bad practice to use Sun's proprietary Java classes?)。

    但是,这允许您“暂停”从 fxApplication 线程调用的方法的执行,直到事件发生。

    使用

    Toolkit.getToolkit().enterNestedEventLoop(loopId);
    

    “暂停”方法和

    Toolkit.getToolkit().exitNestedEventLoop(loopId, value);
    

    恢复方法。

    loopId 需要与Object 相同。

    enterNestedEventLoop 返回传递给exitNestedEventLoop 的值。

    使用这些方法,您可以简单地将动画添加到quicksort 方法,并在步骤完成时“暂停”并从Button 事件处理程序“恢复”执行。

    清洁解决方案

    您基本上将动画的每个状态都保存到一个列表中,以便可以逐步执行:

    更改您的AnimationPane 以支持以下方法:

    • setUpperArrowPosition(int)setPivotArrowPosition(int)setLowerArrowPosition(int) 分别改变上箭头、枢轴和下箭头的位置。
    • swap(int, int) 此方法交换数组中 2 个元素的视觉表示。

    这样你不仅有更简洁的设计,而且更容易将更改操作“保存”到List

    创建一个字段List&lt;Comsumer&lt;AnimationPane&gt;&gt; steps。此列表中的每个元素都会更改 AnimationPane 的状态,以使用上面定义的新方法表示每个步骤之后的状态。在实际进行排序之前,您初始化AnimationPane。然后在排序过程中,您只需将需要对 UI 进行的所有更改作为Consumers 添加到列表中以供以后执行,例如而不是

    while (array[i] < pivot) {
        i++;
    }
    

    使用

    while (array[i] < pivot) {
        i++;
        steps.add(animationPane -> {
             animationPane.setLowerArrowPosition(i);
        });
    }
    

    您可能需要稍微调整算法以正确分组 ui 表示,但这应该不会太难。

    quicksort 方法完成后,您现在有一个 ListComsumers 可用,它们将 UI 更改为各自的下一个状态。您可以简单地使用Iterator 逐步完成动画:

    Iterator<Consumer<AnimationPane>> iter = steps.iterator();
    Button nextButton = new Button("Step");
    button.setOnAction(evt -> {
        if (iter.hasNext()) {
             iter.next().accept(animationPane);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-24
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多