snippetcppMinor
Quicksort using uniform_int_distribution to select the pivot
Viewed 0 times
thepivotquicksortuniform_int_distributionusingselect
Problem
I have not used C++ for a while. Could you please tell me if my usage of the `
Other improvements are also welcome, of course.
module is correct? I am not sure if I need to be creating a new instance of uniform_int_distribution` on each recursive call. I am not sure that I should be seeding the generator on each recursive call. I suspect these two actions need to happen somewhere outside but I do not know.Other improvements are also welcome, of course.
#include
#include
using generator = std::mt19937;
template
void quicksort(iterator fst, iterator lst) {
if (fst >= lst) {return;}
generator g(42);
auto i = fst, j = lst;
auto rval = std::uniform_int_distribution<>(0, std::distance(i, j));
auto pivot = *(fst + rval(g));
while (i
void qsort(iterator begin, iterator end) {
if (begin == end) {return;}
quicksort(begin, end - 1);
}Solution
Because you are creating a generator in each iteration with the same seed, the value you get from your distribution will be the same.
So no, this is not the correct way to use the new random subsystem in C++11.
You need to pass in a distribution by reference to
Also personally I don't feel that random numbers should be a part of a sorting algorithm because performance becomes non-deterministic. I would suggest you use one of the other pivot selection strategies.
Also your algorithm requires the use of random access iterators. Might be worth noting.
So no, this is not the correct way to use the new random subsystem in C++11.
You need to pass in a distribution by reference to
quicksort(iteratorm,iterator).Also personally I don't feel that random numbers should be a part of a sorting algorithm because performance becomes non-deterministic. I would suggest you use one of the other pivot selection strategies.
Also your algorithm requires the use of random access iterators. Might be worth noting.
Context
StackExchange Code Review Q#135586, answer score: 4
Revisions (0)
No revisions yet.