Question

I'm trying to implement QuickSort() using random pivot

When I'm not randomizing pivot, and choosing it to be A[0] everything works fine, but when I implement the randomization things are going crazy.

Partition:

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;
}

QuickSort:

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);
    }
}
Was it helpful?

Solution

Here is an issue:

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

needs to be

pivot = left + rand() % (right - left + 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top