Hi guys, I have a problem I'm trying to solve for a long time. I am supposed to write a quicksort function to sort numbers of integer type from 0 to 1000. This is my code:
void quicksort(int k[], int left, int right)
{
// left is lowest index of array k
// right is highest index of array k
int pivot=k[left], i=left, j=right, swap;
do
{
do
{
i++;
}
while (k[i]<pivot);
do
{
if (i>j)
break;
j--;
}
while (k[j]>pivot);
if (i<j)
{
swap=k[i];
k[i]=k[j];
k[j]=swap;
}
else
{
swap=k[left];
k[left]=k[j];
k[j]=swap;
}
cout << endl << endl;
// testing
// for (int a=0; a<=right; a++)
// {
// cout << k[a] << '\t';
// }
}
while (i<j);
// recursion
if (left<right)
{
quicksort(k, left, j--);
quicksort(k, j++, right);
}
}
I realised by checking the sequence with for-loop that my partitions seems to be working, but not my recursion. I managed to find a sample code that works by using pivot=k[(left+right)/2], but my assignment states that pivot needs to be = k[left].
So, I was wondering how the recursion can be changed so that the function would work.
Thank you for your help! I didn't know that increments and decrements cannot be used in function parameters. Now my recursion seems to be working but there are still some odd errors (the sort gets progressively inaccurate somehow). So does the problem lie with the loops that I am using instead?