我的quicksort实施使用了太多比较,但无法确定原因

时间:2018-10-26 21:14:19

标签: java sorting recursion quicksort

我试图在Java中实现quicksort,但我正在努力以有效的方式实现它。我相信问题出在我的递归调用上,但是我无法确定如何解决它。我正在使用比较来查看比较次数,以期确定问题出在哪里。我唯一想到的就是需要在我的递归语句周围加上条件,因为无论输入数组是否已排序或看似随机,所需的比较量都是相同的。

public int quickSort(int[] arr, int left, int right) {

    //left is lowest index
    //right is highest index

    int compares = 0;

    //calls insertion sort once subsets get smaller than 7 elements
    if (right - left < 6) {
      compares += insertSort(arr, left, right);
      return compares;
    }

        //calculate random pivot
        int pivotIndex = randomInt(left, right);
        int pivotValue = arr[pivotIndex];


        //moves pivot value to rightmost index
        int temp;
        temp = arr[pivotIndex];
        arr[pivotIndex] = arr[right];
        arr[right] = temp;

        int pivotFinal = left;


        //determines how many values are lower than the pivot, swapping 
        //smaller values with larger values along the way
        for (int i = left; i < right; i++) {
            compares++;
            if (arr[i] <= pivotValue) {
                temp = arr[i];
                arr[i] = arr[pivotFinal];
                arr[pivotFinal] = temp;
                pivotFinal++;
            }
        }

        //moves pivot to final position so that quicksort is complete
        temp = arr[pivotFinal];
        arr[pivotFinal] = arr[right];
        arr[right] = temp;

        compares += quickSort(arr, left, pivotIndex - 1);
        compares += quickSort(arr, pivotIndex + 1, right);
        return compares;
}



public void main() {
    QuickSort qs = new QuickSort();

    int n = 60;
    int[] array = qs.GenerateRandomSequence(n);

    int compares = qs.quickSort(array);
}

n为60时,其中一个序列需要进行超过400万次比较,这比实际的最坏情况运行时要差得多。

1 个答案:

答案 0 :(得分:4)

您的索引存在一些错误。您的递归需要使用最终的枢轴位置。

compares += quickSort(arr, left, pivotFinal - 1);
compares += quickSort(arr, pivotFinal + 1, right);

您在不同位置对待“正确”索引的方式有所不同。可能最容易在循环中使用“ <=”

for (int i = left; i < right; i++) // assumes right is after the last index

arr[pivotIndex] = arr[right]; // assumes right IS the last index