Skip to content

<algorithm>: nth_element does not comply with worst case running time requirements #856

Description

Describe the bug
The standard requires nth_element (both std and std::ranges overloads) to perform only O(n lg n) swaps. However, we currently implement only quickselect:

while (_ISORT_MAX < _ULast - _UFirst) { // divide and conquer, ordering partition containing Nth

This has worst case running time O(n^2) if we always choose bad pivots, just like quicksort. We need some form of 'ideal' checking similar to how std::sort works, and fall back to a median-of-medians or similar implementation.

Additional context

This was previously recorded in a Microsoft-internal bug database but I closed the issue there as I had filed it against myself.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!performanceMust go faster

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions