If you want your quicksort to work on arrays and vectors, you have two choices:
1 2 3 4 5 6 7 8 9
template< typename T >
void quicksort( T* first, T* last ) // last = 1 past last element to sort, just as in all stl algorithms
{
}
// and with vectors, you call it like this:
std::vector< int > v;
if( !v.empty() )
quicksort( &v[ 0 ], &v[ v.size() - 1 ] + 1 )
or:
1 2 3 4 5 6 7 8 9 10 11
template< typename RandomAccessIter >
void quicksort( RandomAccessIter first, RandomAccessIter last )
{
}
// and call it like this:
int array[ 10 ];
std::vector< int > v;
quicksort( array, array + 10 );
quicksort( v.begin(), v.end() );
do you know why then this works with arrays and not vectors?
like I said, i am new to vectors but they seem similar to arrays in that you can use the subscripts.
the quicksort works with 'arrayname[10]' but not a vector of length 10.
I guess my main area of confusion comes from the fact that my bubblesort, selectsort, and shell sort work with both arrays and vectors. but I just cannot get quicksort to work.
maybe i will just have to do what jsmith said and use the version of quicksort that takes 2 parameters.
Undefined behaviour is undefined.
You just were unlucky with the array.
Fix those dowhile and it should work.
Edit:
You've got the out of bounds with the array too, it just didn't crash.
When it reached
1 2 3 4
if (j < k)
{
swapitem(temp[j], temp[k]);
}
the condition was false, so you didn't see the error.
If you are worried about out of bounds, replace the subscripts with vector::at. That will raise an exception in case of a bad index.
template <class dType>
void quicksort(dType &temp, int l, int r)
{
int j, k;
if (l < r)
{
j = l;
k = r + 1;
do
{
do{j++;} while ((temp[j] < temp[l]));
do{k--;} while ((temp[k] > temp[l]));
if (j < k)
{
swapitem(temp[j], temp[k]);
}
}
while (k > j);
swapitem(temp[l], temp[k]);
quicksort(temp, l, k - 1);
quicksort(temp, k + 1, r);
}
}
I changed it back to this and it works on both static and dynamic arrays. still not working with vectors.
I have noticed that the version i am trying to use might be an old version because it uses the temp[l] as the pivot point where as most I am seeing online use temp[(left + right) /2] as the pivot point. I am having trouble making my version like the newer version.
this is a slightly modified version of what i found online. and this works for vectors and arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
template <class dType>
void quicksort(dType &temp, int left, int right) {
int i = left, j = right;
int pivot = temp[(left + right) / 2];
while (i <= j)
{
while (temp[i] < pivot)i++;
while (temp[j] > pivot)j--;
if (i <= j)
{
swapitem(temp[i], temp[j]);
i++;
j--;
}
};
if (left < j)quicksort(temp, left, j);
if (i < right)quicksort(temp, i, right);
}