Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
The C++ solution is flawed. srand() should only be called once for the entire du...

Adam Sweeney

Dec 11, 2022

The C++ solution is flawed. srand() should only be called once for the entire duration of a program. In the C++ solution, the function partition() calls srand(), but partition() is recursively called. This means that srand() is called multiple times, and it resets the PRNG every time it is called. If it is called multiple times in the same second, which is extremely likely, you get the exact same value every time, making it no better than the original QuickSelect algorithm. And that's before getting into the whole "rand() considered harmful" subject.

0

0

Comments
Comments
A
Adam Sweeney3 years ago

If you insist on keeping srand(), you typically call it at the beginning of main().

A
Adam Sweeney3 years ago

I forgot to mention which C++ solution. 6. Using Quicksort's Randomized Partitioning Scheme.

On this page