View source code
Display the source code in std/algorithm/sorting.d from which this page was generated on
github.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Page wiki
View or edit the community-maintained wiki page associated with this page.
std.algorithm.sorting.top
- multiple declarations
- Function topN
- Function topN
Function topN
Reorders the range
using r
swap
such that
refers
to the element that would fall there if the range were fully
sorted. In addition, it also partitions r
[nth
]
such that all elements
r
e1
from
to r
[0]
satisfy r
[nth
]!less(
,
and all elements r
[nth
], e1)e2
from
to r
[nth
]
satisfy
r
[r.length]!less(e2,
. Effectively, it finds the r
[nth
])nth
smallest
(according to less
) elements in
. Performs an expected
Ο(r
r.length
) (if unstable) or Ο(r.length * log(r.length)
)
(if stable) evaluations of less
and swap
.
If n >= r.length
, the algorithm has no effect.
Prototype
void topN(alias less, std.algorithm.mutation.SwapStrategy ss, Range)( Range r, size_t nth ) if (isRandomAccessRange!Range && hasLength!Range);
Parameters
Name | Description |
---|---|
less | The predicate to sort by. |
ss | The swapping strategy to use. |
r | The random-access range to reorder. |
nth | The index of the element that should be in sorted position after the function is done. |
See Also
BUGS
Stable topN
has not been implemented yet.
Example
int[] v = [ 25, 7, 9, 2, 0, 5, 21 ]; auto n = 4; topN!"a < b"(v, n); assert(v[n] == 9);
Function topN
Stores the smallest elements of the two ranges in the left-hand range.
Prototype
void topN(alias less, std.algorithm.mutation.SwapStrategy ss, Range1, Range2)( Range1 r1, Range2 r2 ) if (isRandomAccessRange!Range1 && hasLength!Range1 && isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2));
Parameters
Name | Description |
---|---|
less | The predicate to sort by. |
ss | The swapping strategy to use. |
r1 | The first range. |
r2 | The second range. |
Example
int[] a = [ 5, 7, 2, 6, 7 ]; int[] b = [ 2, 1, 5, 6, 7, 3, 0 ]; topN(a, b); sort(a); assert(a == [0, 1, 2, 2, 3]);