Please review the following quicksort implementation.
qsort
below is intentionally unstable, as partition
reoders equal elements.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Ensures pivot is at position end.
template<typename Iter, typename T>
Iter part_pivot(Iter begin, Iter end, T pivot) {
while (begin != end) {
if (*begin < pivot)
++begin;
else if (*--end < pivot)
iter_swap(begin, end);
}
return begin;
}
template<typename Iter>
Iter part(Iter begin, Iter end) {
typename iterator_traits<Iter>::value_type pivot = *begin;
Iter mid = part_pivot(begin, end, pivot);
// Ensure pivot is at position mid.
iter_swap(--end, mid);
return mid;
}
template<class Iter>
void quicksort(Iter begin, Iter end) {
if (std::distance(begin, end) < 2)
return;
Iter mid = part(begin, end, *begin);
quicksort(begin, mid);
quicksort(++mid, end);
}
template<class T>
void quicksort(vector<T>& v) {
quicksort(v.begin(), v.end());
}
template <class T>
void print(const vector<T>& v) {
for (const T& t : v)
cout << t << " ";
cout << endl;
}
int main() {
vector<int> v = {1,4,8,34,2,3,45,6,87,4,3};
print(v);
quicksort(v);
print(v);
}
qsort
is advisable. It isn't that great of a name unless you're using a 1970s-era compiler that limited identifier names to 6–8 characters.) Speaking of the standard library, why aren't you just usingstd::sort
? That makes it hard to review the code: since you are including<algorithm>
, I'd want to recommend using, e.g.,std::swap
, but then the existence ofstd::sort
makes the whole exercise rather silly. \$\endgroup\$qsort(mid, end);
for me. \$\endgroup\$