@@ -194,6 +194,8 @@ mod group_map;
194
194
mod groupbylazy;
195
195
mod intersperse;
196
196
#[ cfg( feature = "use_alloc" ) ]
197
+ mod k_smallest;
198
+ #[ cfg( feature = "use_alloc" ) ]
197
199
mod kmerge_impl;
198
200
#[ cfg( feature = "use_alloc" ) ]
199
201
mod lazy_buffer;
@@ -2284,6 +2286,39 @@ pub trait Itertools : Iterator {
2284
2286
v. into_iter ( )
2285
2287
}
2286
2288
2289
+ /// Sort the k smallest elements into a new iterator, in ascending order.
2290
+ ///
2291
+ /// **Note:** This consumes the entire iterator, and returns the result
2292
+ /// as a new iterator that owns its elements.
2293
+ ///
2294
+ /// This is guaranteed to use `k * sizeof(Self::Item) + O(1)` memory
2295
+ /// and `O(n log k)` time, with `n` the number of elements in the input.
2296
+ ///
2297
+ /// The sorted iterator, if directly collected to a `Vec`, is converted
2298
+ /// without any extra copying or allocation cost.
2299
+ ///
2300
+ /// ```
2301
+ /// use itertools::Itertools;
2302
+ ///
2303
+ /// // A random permutation of 0..15
2304
+ /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
2305
+ ///
2306
+ /// let five_smallest = numbers
2307
+ /// .into_iter()
2308
+ /// .k_smallest(5);
2309
+ ///
2310
+ /// itertools::assert_equal(five_smallest, 0..5);
2311
+ /// ```
2312
+ #[ cfg( feature = "use_alloc" ) ]
2313
+ fn k_smallest ( self , k : usize ) -> VecIntoIter < Self :: Item >
2314
+ where Self : Sized ,
2315
+ Self :: Item : Ord
2316
+ {
2317
+ crate :: k_smallest:: k_smallest ( self , k)
2318
+ . into_sorted_vec ( )
2319
+ . into_iter ( )
2320
+ }
2321
+
2287
2322
/// Collect all iterator elements into one of two
2288
2323
/// partitions. Unlike `Iterator::partition`, each partition may
2289
2324
/// have a distinct type.
0 commit comments