为什么我的快速排序溢出

Why is my QuickSort overflowing?

本文关键字:溢出 快速排序 我的 为什么      更新时间:2023-10-16

我正在尝试使用随机枢轴实现QuickSort()

当我不随机化枢轴,并选择它为A[0]时,一切都很好,但当我实现随机化时,事情就变得疯狂了。

分区:

int Partition(int A[], int left, int right, int pivot = 0)
{
    swap(A[left], A[pivot]);
    int temp = right;
    while (pivot != temp)
    {
        // make a swap if needed
        if (A[pivot] > A[temp] && temp > pivot || A[temp] > A[pivot] && temp < pivot)
        {
            // swap both data and index
            swap(A[pivot], A[temp]);
            swap(pivot, temp);
        }
        // advance the temp towards pivot
        if (temp < pivot)
            temp++;
        else
            temp--;
    }
return pivot;
}

快速排序:

void QuickSort(int A[], int left, int right)
{
    int pivot;
    if (left < right) {
        // randomize pivot
        srand(time(NULL));
        pivot = rand() % (right - left + 1);
        // partition and call quicksort
        pivot = Partition(A, left, right, pivot);
        QuickSort(A, left, pivot - 1);
        QuickSort(A, pivot + 1, right);
    }
}

这里有一个问题:

pivot = rand() % (right - left + 1);

需要

pivot = left + rand() % (right - left + 1);