I found this code for quicksort with a fixed pivot. It always takes a right-hand side element of the given table as a pivot. I want it to take a random element as a pivot. I think that x is a pivot here, so I thought it was a good idea to change it to a random element from a given list, but it turns out that it is not working.
void swap ( int* a, int* b )
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int l, int h)
{
int x = arr[h];
int i = (l - 1);
for (int j = l; j <= h- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[h]);
return (i + 1);
}
void quickSortIterative (int arr[], int l, int h)
{
int stack[ h - l + 1 ];
int top = -1;
stack[ ++top ] = l;
stack[ ++top ] = h;
while ( top >= 0 )
{
h = stack[ top-- ];
l = stack[ top-- ];
int p = partition( arr, l, h );
if ( p-1 > l )
{
stack[ ++top ] = l;
stack[ ++top ] = p - 1;
}
if ( p+1 < h )
{
stack[ ++top ] = p + 1;
stack[ ++top ] = h;
}
}
}
I tried changing lines
int x = arr[h];
and
swap(&arr[i+1], &arr[j]);
to
int r = l+rand()%(h-l);
int x = arr[r];
and then
swap(&arr[i+1], &arr[r]);
but it is not sorting properly. Obviously I'm doing something wrong here. Please help.