繁体   English   中英

需要帮助JAVA quicksort递归

[英]Need assistance JAVA quicksort recursion

对于学校,我必须为数组数组编写快速排序。 我认为我的分区很好,但是递归总是出错。

public static int partition(String[] input, int max) {
    // pivot is dividing point
    // I keeps track of lesser values
    // count is just a counter
    // Pivots in place
    int pivot = 0;
    int i = 1;
    int count = 1;

    while (count <= max) {
        if (input[count].compareTo(input[pivot]) < 0) {
            input[i] = input[count];
            i = i + 1;
        }
        if (count == max) {
            input[i] = input[pivot];
            input[pivot] = input[i];
        }
        count++;
    }
    return pivot;
}

public static void qSort(String[] input) {
    int index = partition(input, input.length - 1);
    int count = 0;
    if (count < index - 1) {
        partition(input, index - 1);
    }
    if (index + 1 < count && count < input.length) {
        partition(input, input.length - 1);
    }
    count++;
}

您的实现有很多错误。 首先,您始终选择轴作为要在数组索引0处的元素。 quicksort的思想是选择一些枢轴,在其周围对数组进行分区,然后在所选枢轴周围的两个分区上递归应用quicksort。 如何确定将递归调用quicksort的分区的开始和结束? 您需要像其他注释中提到的那样将那些参数作为参数传递给分区方法,对于quicksort方法本身也是如此。

public void swap (String [] array, int i, int j) {
    String tmp = array[i];
    array[i] = array[j];
    array[j] = tmp;
}

public static int partition (String [] array, int low, int high) {
    String pivot = array[low];
    int index = low+1;
    for (int i = low+1; i <= high; i++) {
        if (pivot.compareTo(array[i]) > 0) {
            swap(array, i, index);
            index++;
        }
    }
    swap(array, low, index-1);
    return index-1;
}

public static void qsort(String [] array, int low, int high) {
    if (low < high) {
        int p = partition(array, low, high);
        qsort(array, low, p);
        qsort(array, p+1, high);
    }
}

显然,这不是选择枢轴的最佳方法,因为某些数组会使算法的性能非常差。 更好的方法是每次使用随机枢轴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM