javaFX:错误的合并排序动画结果

时间:2017-03-24 21:34:07

标签: java algorithm sorting javafx mergesort

我正在使用javaFX实现一些带有一些矩形的合并排序动画。我使用动画的一些功能来做到这一点。但是,翻译路线是错误的。我一遍又一遍地检查我的代码,但没有发现问题。问题可能出在合并方法中,但我无法找到问题所在。我使用绝对坐标来定位节点:javaFX:move shapes with absolute coordinates using translatetransition。谁能帮助我?

这些是代码:

public class Main extends Application {
double speed = 400;

int[] helper;

final ArrayList<Integer> CenterX = new ArrayList();
int listindex = 0;
@Override
public void start(Stage primaryStage) throws Exception {

    Pane pane = new Pane();
    ArrayList<StackPane> list = new ArrayList<>();
    Random random = new Random(5);
    for (int i = 0; i < 13; i++) {
        int num = random.nextInt(10);
        Rectangle rectangle = new Rectangle(40, (num * 10) + 50);
        rectangle.setFill(Color.valueOf("#FF7F50"));
        Text text = new Text(String.valueOf(num));
        StackPane stackPane = new StackPane();
        stackPane.setPrefSize(rectangle.getWidth(), rectangle.getHeight());
        stackPane.setId(String.valueOf(num));
        stackPane.getChildren().addAll(rectangle, text);
        StackPane.setAlignment(text,Pos.TOP_CENTER);
        stackPane.setAlignment(Pos.TOP_CENTER);
        stackPane.setTranslateX(60*i);
        list.add(stackPane);
    }


    pane.getChildren().addAll(list);

    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(pane);
    HBox hBox1 = new HBox();
    Button b = new Button("Sort");


    AnchorPane bottomPane = new AnchorPane();
    hBox1.getChildren().add(b);
    bottomPane.getChildren().add(hBox1);     
    borderPane.setBottom(bottomPane);


    b.setOnAction(event -> {
        SequentialTransition sq = new SequentialTransition();
        int[] = arr;
        arr = generateArray(list);
        sq = MergeSort(arr, list,sq);
        b.setDisable(true);
        sq.play();
        sq.setOnFinished(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                b.setDisable(false);
            }
        });
        b.setDisable(false);

    });

    Scene scene = new Scene(borderPane,800, 800);
    primaryStage.setTitle("Sorting");
    primaryStage.setResizable(false);
    primaryStage.setScene(scene);
    primaryStage.show();

    for (int i = 0; i < 13; i++) {
        int centerx = (int) list.get(i).getLayoutX();
        CenterX.add(i,centerx+60*i);
        System.out.println(centerx+60*i);

    }
}



private int[] generateArray(List<StackPane> list) {
    int arr[] = new int[list.size()];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = Integer.parseInt(list.get(i).getId());
    }
    return arr;
}

private TranslateTransition AddtoOriginal(StackPane sp, double speed,int X){
    TranslateTransition t = new TranslateTransition();
    t.setNode(sp);
    t.setDuration(Duration.millis(speed));
    t.setToX(X);
    t.setToY(300);
    return t;

}

public SequentialTransition MergeSort(int arr[],ArrayList<StackPane> list,SequentialTransition sq) {
    int number = arr.length;
    this.helper = new int[number];
    mergesort(0, number - 1,arr,sq,list);
    return sq;
}

private void mergesort(int low, int high,int arr[],SequentialTransition sq,ArrayList<StackPane> list) {
    // check if low is smaller then high, if not then the array is sorted
    if (low < high) {
            // Get the index of the element which is in the middle
            int middle = low + (high - low) / 2;
            // Sort the left side of the array
            mergesort(low, middle,arr,sq,list);
            // Sort the right side of the array
            mergesort(middle + 1, high,arr,sq,list);
            // Combine them both
            merge(low, middle, high,arr,list,sq);
    }

}


private void merge(int low, int middle, int high,int arr[],ArrayList<StackPane> list,SequentialTransition sq) {
// Copy both parts into the helper array
    for (int i = low; i <= high; i++) {
            helper[i] = arr[i];

    }
    int i = low;
    int j = middle + 1;
    int k = low;
    // Copy the smallest values from either the left or the right side back
    // to the original array

    while (i <= middle && j <= high) {
            if (helper[i] <= helper[j]) {
                    arr[k] = helper[i];
                    sq.getChildren().add(AddtoOriginal(list.get(i),speed,CenterX.get(k)));
                    i++;
            } else {
                    arr[k] = helper[j];
                    sq.getChildren().add(AddtoOriginal(list.get(j),speed,CenterX.get(k)));
                    j++;
            }
            k++;
    }
    // Copy the rest of the left side of the array into the target array
    while (i <= middle) {
            arr[k] = helper[i];
            sq.getChildren().add(AddtoOriginal(list.get(i),speed,CenterX.get(k)));
            k++;
            i++;
    }

    ParallelTransition pl = new ParallelTransition();
    ArrayList<TranslateTransition> Transitionlist = new ArrayList<>(high-low);

    for (int z = low; z <= high; z++) {
        TranslateTransition t = new TranslateTransition();
        t.setNode(list.get(z));
        t.setDuration(Duration.millis(speed));
        t.setByY(-300);
        Transitionlist.add(t);  
}
pl.getChildren().addAll(Transitionlist);
sq.getChildren().add(pl);

}

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

1 个答案:

答案 0 :(得分:1)

您的代码问题以及如何解决这些问题

你的主要问题是当你做这样的事情时:

arr[k] = helper[j];
sq.getChildren().add(AddtoOriginal(list.get(j),speed,CenterX.get(k)));

你正在做的是有一些数组(arrhelper)代表被排序的值,你移动数组中位置内的值(在赋值中),但当你运行AddToOriginal例程,您也不会移动列表中代表可视显示的值。所以发生的事情是视觉显示与排序的数组不同步。

合并排序算法(正如你实现的那样)在内存中并不是一个排序,实际上涉及两个数组,arr数组和helper数组,帮助器是分配arr值时必须跟踪原始值,以便不会覆盖原始值。你需要用可视化表示做同样的事情。对于我在下面根据您的原始代码实现的示例代码,我所做的是添加一个额外的helperNodes数组,它跟踪辅助数组的位置引用,但是以可视形式。

将这两者放在一起,无论何时交换节点,都要执行这样的额外语句,以使可视列表与您正在操作的值数组内联:

arr[k] = helper[j];
list.set(k, helperNodes[j]);
sq.getChildren().add(move(helperNodes[j], k * SPACING));

另请注意,交换移动基于未突变的helperNodes[j]元素,而不是list.get(j)元素,这些元素可能已经被突变。上面的代码正在做的是通过操纵可视列表数组和sq顺序转换中的动画移动来镜像值赋值的逻辑。

另外一个问题是,当要排序的合并段的右侧部分中的节点已按顺序排列时,用于合并排序的算法不会执行任何操作。但是,您正在执行合并段中所有元素的动画移动,直到其原始起始高度。因此,即使数组中的值位置没有改变,您也需要添加一些额外的代码来执行该可视化动画。

如果您发现这很困难,请不要担心(这并不像IMO那样容易: - )

信用卡

我猜测(可能是错误的)您的合并排序算法基于Vogella Merge Sort Tutorial。如果是这样,很高兴承认在问题中,因为它有助于理解上下文中的灵感来源(如果没有,你可以忽略这个注释)。

未排序

unsorted

正在进行排序

in progress

排序

sorted

示例应用

import javafx.animation.*;
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.util.*;

public class Merge extends Application {
    private static final int N_VALUES = 13;
    private static final int SPACING = 60;
    private static final int SORT_GROUP_MOVE_DELTA = 200;

    private static final Duration SPEED = Duration.millis(400);

    private int[] helper;
    private StackPane[] helperNodes;
    private Random random = new Random(5);

    @Override
    public void start(Stage stage) throws Exception {
        Pane displayPane = new Pane();
        ArrayList<StackPane> list = new ArrayList<>();
        for (int i = 0; i < N_VALUES; i++) {
            StackPane stackPane = createValueNode(i);
            list.add(stackPane);
        }

        displayPane.getChildren().addAll(list);

        Button sortButton = new Button("Sort");
        sortButton.setOnAction(event -> {
            SequentialTransition sq = new SequentialTransition();
            int[] arr = generateArray(list);
            sq = mergeSort(arr, list, sq);
            sortButton.setDisable(true);
            sq.play();
            sq.setOnFinished(event1 -> sortButton.setDisable(false));
            sortButton.setDisable(false);
        });

        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(displayPane);
        borderPane.setBottom(sortButton);
        BorderPane.setAlignment(sortButton, Pos.CENTER);
        BorderPane.setMargin(sortButton, new Insets(10));

        Scene scene = new Scene(borderPane, 800, 400);
        stage.setTitle("Sorting");
        stage.setResizable(false);
        stage.setScene(scene);
        stage.show();
    }

    private StackPane createValueNode(int i) {
        int num = random.nextInt(10);
        Rectangle rectangle = new Rectangle(40, (num * 10) + 50);
        rectangle.setFill(Color.valueOf("#FF7F50"));
        Text text = new Text(String.valueOf(num));
        StackPane stackPane = new StackPane();
        stackPane.setPrefSize(rectangle.getWidth(), rectangle.getHeight());
        stackPane.setId(String.valueOf(num));
        stackPane.getChildren().addAll(rectangle, text);
        StackPane.setAlignment(text, Pos.TOP_CENTER);
        stackPane.setAlignment(Pos.TOP_CENTER);
        stackPane.setTranslateX(SPACING * i);
        return stackPane;
    }


    private int[] generateArray(List<StackPane> list) {
        int arr[] = new int[list.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Integer.parseInt(list.get(i).getId());
        }
        return arr;
    }

    private TranslateTransition move(StackPane sp, int X) {
        TranslateTransition t = new TranslateTransition();
        t.setNode(sp);
        t.setDuration(SPEED);
        t.setToX(X);
        t.setToY(SORT_GROUP_MOVE_DELTA);
        return t;

    }

    public SequentialTransition mergeSort(int arr[], ArrayList<StackPane> list, SequentialTransition sq) {
        int number = arr.length;
        this.helper = new int[number];
        this.helperNodes = new StackPane[number];
        sortRange(0, number - 1, arr, sq, list);
        return sq;
    }

    private void sortRange(int low, int high, int arr[], SequentialTransition sq, ArrayList<StackPane> list) {
        // check if low is smaller then high, if not then the array is sorted
        if (low < high) {
            // Get the index of the element which is in the middle
            int middle = low + (high - low) / 2;
            // Sort the left side of the array
            sortRange(low, middle, arr, sq, list);
            // Sort the right side of the array
            sortRange(middle + 1, high, arr, sq, list);
            // Combine them both
            merge(low, middle, high, arr, list, sq);
        }
    }


    private void merge(int low, int middle, int high, int arr[], ArrayList<StackPane> list, SequentialTransition sq) {
        // Copy both parts into the helper array
        for (int i = low; i <= high; i++) {
            helper[i] = arr[i];
            helperNodes[i] = list.get(i);
        }

        int i = low;
        int j = middle + 1;
        int k = low;
        // Copy the smallest values from either the left or the right side back
        // to the original array

        while (i <= middle && j <= high) {
            if (helper[i] <= helper[j]) {
                arr[k] = helper[i];
                list.set(k, helperNodes[i]);
                sq.getChildren().add(move(helperNodes[i], k * SPACING));
                i++;
            } else {
                arr[k] = helper[j];
                list.set(k, helperNodes[j]);
                sq.getChildren().add(move(helperNodes[j], k * SPACING));
                j++;
            }
            k++;
        }
        // Copy the rest of the left side of the array into the target array
        while (i <= middle) {
            arr[k] = helper[i];
            list.set(k, helperNodes[i]);
            sq.getChildren().add(move(helperNodes[i], k * SPACING));
            k++;
            i++;
        }

        // Even if we didn't move in the array because it was already ordered, 
        // move on screen for any remaining nodes in the target array.
        while (j <= high) {
            sq.getChildren().add(move(helperNodes[j], k * SPACING));
            k++;
            j++;
        }

        ParallelTransition moveUp = new ParallelTransition();

        for (int z = low; z <= high; z++) {
            TranslateTransition moveNodeUp = new TranslateTransition();
            moveNodeUp.setNode(helperNodes[z]);
            moveNodeUp.setDuration(SPEED);
            moveNodeUp.setByY(-SORT_GROUP_MOVE_DELTA);
            moveUp.getChildren().add(moveNodeUp);
        }

        sq.getChildren().add(moveUp);
    }

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

可能的替代实施

您可以做的一件事是创建一个SortableNode类来替换您定义的StackPane来保存值。可排序节点可以将节点的值保留在字段中而不是ID中。可排序节点还可以实现Comparable。然后可以更新合并排序算法以将可比较对象列表作为输入而不是整数数组。这样,您就不需要跟踪排序中值和可视表示的单独数组 算法(并保持同步)。这可能会略微简化实施。但是我不会在这里添加额外的示例来实现这种替代方法(因为上面的当前示例似乎工作正常; - )