打印每次通过的合并排序和快速排序算法

时间:2018-10-03 06:07:18

标签: java algorithm sorting

我正在尝试输出为作业分配的“合并排序”和“快速排序”算法的每个遍历,但是在弄清楚要打印什么,何时打印以及在何处放置时有点困难打印声明。除了打印值之外,还需要每次遍历用括号括住算法创建的数组,如下所示:


合并排序样本所需的输出:

[ 4     85     94     68     76     75     40     66     18 ]
[ 4     85     94     68     76 ] [ 75     40     66     18 ]
[ 4     85     94 ] [ 68     76 ] [ 75     40 ] [ 66     18 ]
[ 4     85 ] [ 94 ] [ 68 ] [ 76 ] [ 75 ] [ 40 ] [ 66 ] [ 18 ]
[ 4     85 ] [ 94 ]    
[ 4 ] [ 85 ]  
[ 4     85 ]    
[ 4     85     94 ] [ 68     76 ] [ 40     75 ] [ 18     66 ] 
[ 4     68     76     85     94 ] [ 18     40     66     75 ]
[ 4     18     40     66     68     75     76     85     94 ]

所需样品的快速排序输出:

[ 47     44     39     77     80     19     49     45     65 ]
[ 44     39     19     45 ] [ 47 ] [ 77     80     49     65 ]
[ 39     19 ] [ 44 ] [ 45 ] [ 47 ] [ 49     65 ] [ 77 ] [ 80 ]
[ 19 ] [ 39 ] [ 44 ] [ 45 ] [ 47 ] [ 49 ] [ 65 ] [ 77 ] [ 80 ]



我的课程几乎没有涉及堆栈和递归函数,因此我目前有点受困。这是每种排序算法的两个函数:


合并排序算法:

public static void MergeSort(int[] array) {
    int size = array.length;
    if (size < 2)
        return;
    int mid = size / 2;
    int leftSize = mid;
    int rightSize = size - mid;
    int[] left = new int[leftSize];
    int[] right = new int[rightSize];

    for (int i = 0; i < mid; i++) {
        left[i] = array[i];

    }

    for (int i = mid; i < size; i++) {
        right[i - mid] = array[i];
    }

    MergeSort(left);
    MergeSort(right);
    Merge(array, left, right);
}

public static void Merge(int[] array, int[] left, int[] right) {
    int leftSize = left.length;
    int rightSize = right.length;
    int i = 0, j = 0, k = 0;

    while (i < leftSize && j < rightSize) {
        if (left[i] <= right[j]) {
            array[k] = left[i];
            i++;
            k++;
        } else {
            array[k] = right[j];
            k++;
            j++;
        }
    }

    while (i < leftSize) {
        array[k] = left[i];
        k++;
        i++;
    }

    while (j < rightSize) {
        array[k] = right[j];
        k++;
        j++;
    }
}


快速排序:

public static void QuickSort(int[] array, int left, int right) {
    int pivotIndex = left + (right - left) / 2;
    int pivotValue = array[pivotIndex];

    int i = left;
    int j = right;

    while(i <= j) {
        while(array[i] < pivotValue) {
            i++;
        }

        while(array[j] > pivotValue) {
            j--;
        }

        if(i <= j) {
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
            i++;
            j--;
        }

        if(left < i) {
            QuickSort(array, left, j);
        }

        if(right > i) {
            QuickSort(array, i, right);
        }
    }
}

0 个答案:

没有答案