Skip to content

Commit

Permalink
k_smallest(1) and variants: use min[_by]
Browse files Browse the repository at this point in the history
Like with `tail(1)`, I think we should leverage a possible faster specialization.
  • Loading branch information
Philippe-Cholet committed Apr 4, 2024
1 parent e6c9411 commit 1ef5453
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/k_smallest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ where
iter.last();
return Vec::new();
}
if k == 1 {
return iter.min_by(comparator).into_iter().collect();
}
let mut iter = iter.fuse();
let mut storage: Vec<I::Item> = iter.by_ref().take(k).collect();

Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2975,6 +2975,9 @@ pub trait Itertools: Iterator {
self.last();
return Vec::new().into_iter();
}
if k == 1 {
return self.min().into_iter().collect_vec().into_iter();
}

let mut iter = self.fuse();
let mut heap: BinaryHeap<_> = iter.by_ref().take(k).collect();
Expand Down

0 comments on commit 1ef5453

Please sign in to comment.