@@ -2,11 +2,43 @@ use alloc::vec::Vec;
2
2
use core:: cmp:: { Ordering , Reverse } ;
3
3
4
4
/// Consumes a given iterator, returning the minimum elements in **ascending** order.
5
- pub ( crate ) fn k_smallest_general < I : Iterator , F : FnMut ( & I :: Item , & I :: Item ) -> Ordering > (
6
- mut iter : I ,
7
- k : usize ,
8
- mut comparator : F ,
9
- ) -> Vec < I :: Item > {
5
+ pub ( crate ) fn k_smallest_general < I , F > ( mut iter : I , k : usize , mut comparator : F ) -> Vec < I :: Item >
6
+ where
7
+ I : Iterator ,
8
+ F : FnMut ( & I :: Item , & I :: Item ) -> Ordering ,
9
+ {
10
+ /// Sift the element currently at `origin` **away** from the root until it is properly ordered
11
+ fn sift_down < T , F > ( heap : & mut [ T ] , comparator : & mut F , mut origin : usize )
12
+ where
13
+ F : FnMut ( & T , & T ) -> Ordering ,
14
+ {
15
+ fn children_of ( n : usize ) -> ( usize , usize ) {
16
+ ( 2 * n + 1 , 2 * n + 2 )
17
+ }
18
+
19
+ while origin < heap. len ( ) {
20
+ let ( left_idx, right_idx) = children_of ( origin) ;
21
+ if left_idx >= heap. len ( ) {
22
+ return ;
23
+ }
24
+
25
+ let replacement_idx = if right_idx < heap. len ( )
26
+ && Ordering :: Less == comparator ( & heap[ left_idx] , & heap[ right_idx] )
27
+ {
28
+ right_idx
29
+ } else {
30
+ left_idx
31
+ } ;
32
+
33
+ if Ordering :: Less == comparator ( & heap[ origin] , & heap[ replacement_idx] ) {
34
+ heap. swap ( origin, replacement_idx) ;
35
+ origin = replacement_idx;
36
+ } else {
37
+ return ;
38
+ }
39
+ }
40
+ }
41
+
10
42
if k == 0 {
11
43
return Vec :: new ( ) ;
12
44
}
59
91
{
60
92
move |a| Reverse ( f ( a) )
61
93
}
62
-
63
- /// Sift the element currently at `origin` **away** from the root until it is properly ordered
64
- fn sift_down < T , F : FnMut ( & T , & T ) -> Ordering > (
65
- heap : & mut [ T ] ,
66
- comparator : & mut F ,
67
- mut origin : usize ,
68
- ) {
69
- fn children_of ( n : usize ) -> ( usize , usize ) {
70
- ( 2 * n + 1 , 2 * n + 2 )
71
- }
72
-
73
- while origin < heap. len ( ) {
74
- let ( left_idx, right_idx) = children_of ( origin) ;
75
- if left_idx >= heap. len ( ) {
76
- return ;
77
- }
78
-
79
- let replacement_idx = if right_idx < heap. len ( )
80
- && Ordering :: Less == comparator ( & heap[ left_idx] , & heap[ right_idx] )
81
- {
82
- right_idx
83
- } else {
84
- left_idx
85
- } ;
86
-
87
- if Ordering :: Less == comparator ( & heap[ origin] , & heap[ replacement_idx] ) {
88
- heap. swap ( origin, replacement_idx) ;
89
- origin = replacement_idx;
90
- } else {
91
- return ;
92
- }
93
- }
94
- }
0 commit comments