如何在Java矩阵中保存quicksort的每个步骤?

时间:2019-12-17 21:33:22

标签: java matrix quicksort

我很难保存排序快速步骤的每个步骤。我写了这个,但是没有打印任何东西... 我想使Javafx应用程序具有可以按下下一步按钮的功能,它使一步和后退按钮退后一步。因此,我将运行整个quicksort并将所有迭代保存到矩阵中,稍后,我将显示单击下一步并返回的矩阵bz的每一列。因此,我想从一开始就进行分层,但是我坚持保存步骤。

编辑: 附言我知道应该在每一步都打印矩阵,而我不希望那样,以后我会添加一些条件。

public class QS {
    public static void main(String[] args) {
        int[] x = { 9, 2, 4, 7, 3, 7, 10 };
        System.out.println(Arrays.toString(x));

        final int [] [] test  = {
            {1,2,3},
            {4,5,6},
            {7,8,9}
        };

        //for (int p = 0; p < test.length; p++){
        //    for (int k = 0; k < test[p].length; k++){
        //        System.out.print(test[p][k] + " ");
        //    }
        //    System.out.println();
        //}

        int low = 0;
        int high = x.length - 1;
        quickSort(x, low, high);
        System.out.println(Arrays.toString(x));
        int [] [] save = new int [9] [x.length];
    }

    public static void quickSort(int[] arr, int low, int high) {
        if (arr == null || arr.length == 0)
            return;

        if (low >= high)
            return;

        // pick the pivot
        int middle = low + (high - low) / 2;
        int pivot = arr[middle];

        // make left < pivot and right > pivot
        int i = low, j = high;
        while (i <= j) {
            while (arr[i] < pivot)
                i++;

            while (arr[j] > pivot)
                j--;

            if (i <= j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }

        int[][] save = new int[9][arr.length];
        int index = 0;
        // recursively sort two sub parts
        if (low < j)
            quickSort(arr, low, j);

        for (int h=0; h>arr.length+1; h++){
            save [index] [h] = arr [h];
            index++;

            for (int e = 0; e < save.length; e++) {
                for (int f = 0; f < save[e].length; f++) {
                    System.out.print(save[e][f] + " ");
                }

                System.out.println();
            }
        }

        if (high > i)
            quickSort(arr, i, high);

        for (int h=0; h>arr.length+1; h++){
            save [index] [h] = arr [h];
            index++;

            for (int e = 0; e < save.length; e++) {
                for (int f = 0; f < save[e].length; f++) {
                    System.out.print(save[e][f] + " ");
                }

                System.out.println();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在这样的for循环中:

for (int h=0; h>arr.length+1; h++){/*code*/}

大概是小于号:

for (int h=0; h<arr.length+1; h++){/*code*/}

否则,h始终大于arr.length + 1,使条件为false,并且循环仅在此处停止。