[libcxx-commits] [PATCH] D141205: [libcxx] nth_element use introselect to avoid quadratic behavior

Zhikai Zeng via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jan 9 05:21:45 PST 2023


Backl1ght added inline comments.


================
Comment at: libcxx/include/__algorithm/nth_element.h:104
+        {
+            // fall back to heap select.
+            std::__heap_select<_AlgPolicy, _Compare>(__first, __nth, __last, __comp);
----------------
danlark wrote:
> Mordante wrote:
> > Can you add comment why this is done? Currently the comment and the code tell the same thing.
> > For maintainability it would be very good to know why we switch the algorithm.
> Even though I am in favor of this patch, this does not fully fix the issue. With the comparator that changes the inputs on the fly, it's possible to get into a O(n log n) average case.
> 
> Otherwise LGTM, thanks!
I think the average time complexity of introselect should be O(n), since the average time complexity of quickselect is O(n), and according to the original paper of introselect:

> If as in introsort we limit the depth to a logarithmic bound the average time remains linear but the worst case is O(N log N). 


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D141205/new/

https://reviews.llvm.org/D141205



More information about the libcxx-commits mailing list