<algorithm>: nth_element could be more efficient using a binary partition operation
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 11.1k
- Forks
- 1.7k
- Avg merge
- 4d 15h
- Merged PRs (30d)
- 22
Description
Describe the bug
Our partition based sorts like quicksort and quickselect (powering std::sort/std::ranges::sort and std::nth_element/std::ranges::nth_element, respectively) use a very complex tripartite partition operation which partitions the input into 3 ranges: those elements below the pivot, those elements equal to the pivot, and those elements greater than the pivot. See:
When fully sorting the input, this detection of elements equal to the pivot tends to give our sort better behavior than several of our competitors, so for sort we would want to keep such behavior. However, in nth_element, grouping all the equal elements together is extra work we do not need, so a classic binary partition operation would probably produce faster results. Note the call to the very complex partition op followed by additional branches to early-exit if the nth_element is equal to the pivot:
To resolve this report, we should add a benchmark that tests nth_element with inputs large enough to trigger quickselect (which means they must be greater than _ISORT_MAX) to determine if the change is really a win.
Additional context
This is a replay of Microsoft-internal VSO-125613
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in stl/inc/algorithm at the partition operation around line 4036 and the nth_element call around line 4471; note the _ISORT_MAX threshold for quickselect. Add a benchmark using inputs larger than _ISORT_MAX, then compare nth_element behavior with the existing tripartite partition against a binary partition to determine whether the change is a measurable win.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- performance
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100