I have two different implementations of quicksort below. I have verified that oth of these versions of quicksort work in the sense that they will sort any array I give it correctly. If you notice (at least it appears to me), Version #2 is exactly the same as Version #1 when the array size n is greater than 8. Therefore, I would expect that when I give both of these functions an array of the same size that is greater than 8, they should make around the same number of component wise comparisons on average, but they do not.
For n > 8, both functions use sort3() and partition() functions. I have listed those below as well to show you how I count the number of component wise comparisons.
I know that W(n), the theoretical worst case number of comparisons for these implementations of quicksort is (n(n+2)/4)+8. Therefore, for an array size n = 500, W(n) = 62758. For a test run on an array of size n = 500, Version #1 makes about 5000 comparisons on average which is reasonable. However, Version #2 is making 80000 comparisons on average. Obviously this can’t be right – Version #2 is making more comparisons than the theoretical W(n) and it is exactly (at least appears to me) the same algorithm as Version #1.
Do you see an error that I am making in Version #2?
Version #1:
void Quicksort_M3(int S[], int low, int hi)
{
if(low < hi)
{
if((low+1) == hi)
{
comparisons++;
if(S[low] > S[hi])
swap(S[low],S[hi]);
}
else
{
Sort3(S,low,hi);
if((low+2)<hi)
{
swap(S[low+1],S[(low+hi)/2]);
int q = partition(S, low+1, hi-1);
Quicksort_M3(S, low, q-1);
Quicksort_M3(S, q+1, hi);
}
}
}
}
Version #2:
void Quicksort_Insert_M3(int S[], int n, int low, int hi)
{
if((hi-low)<=8)
Insertionsort(S,n);
else
{
if(low < hi)
{
if((low+1) == hi)
{
comparisons++;
if(S[low] > S[hi])
swap(S[low],S[hi]);
}
else
{
Sort3(S,low,hi);
if((low+2)<hi)
{
swap(S[low+1],S[(low+hi)/2]);
int q = partition(S, low+1, hi-1);
Quicksort_Insert_M3(S, n, low, q-1);
Quicksort_Insert_M3(S, n, q+1, hi);
}
}
}
}
}
Partition:
int partition(int *S,int l, int u)
{
int x = S[l];
int j = l;
for(int i=l+1; i<=u; i++)
{
comparisons++;
if(S[i] < x)
{
j++;
swap(S[i],S[j]);
}
}
int p = j;
swap(S[l],S[p]);
return p;
}
Sort3:
int Sort3(int list[], int p, int r)
{
int median = (p + r) / 2;
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
}
else
{
exchange(list,median,r);
}
}
else
;
}
else
{
comparisons++;
if(list[p] > list[r])
{
comparisons++;
if(list[median] < list[r])
{
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
}
else
{
exchange(list,p,r);
}
}
else
{
exchange(list,p,median);
}
}
return list[r];
}
I think your error is that when you do the insertion sort you are still using the original size of the array. Therefore you end up doing an insertion sort on the whole array.