-
Notifications
You must be signed in to change notification settings - Fork 319
Adding _by, by_key, largest variants of k_smallest #654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,96 @@ | ||
use alloc::collections::BinaryHeap; | ||
use core::cmp::Ord; | ||
use alloc::vec::Vec; | ||
use core::cmp::Ordering; | ||
|
||
/// Consumes a given iterator, returning the minimum elements in **ascending** order. | ||
pub(crate) fn k_smallest_general<I, F>(mut iter: I, k: usize, mut comparator: F) -> Vec<I::Item> | ||
where | ||
I: Iterator, | ||
F: FnMut(&I::Item, &I::Item) -> Ordering, | ||
{ | ||
/// Sift the element currently at `origin` away from the root until it is properly ordered. | ||
/// | ||
/// This will leave **larger** elements closer to the root of the heap. | ||
fn sift_down<T, F>(heap: &mut [T], is_less_than: &mut F, mut origin: usize) | ||
where | ||
F: FnMut(&T, &T) -> bool, | ||
{ | ||
#[inline] | ||
fn children_of(n: usize) -> (usize, usize) { | ||
(2 * n + 1, 2 * n + 2) | ||
} | ||
|
||
while origin < heap.len() { | ||
let (left_idx, right_idx) = children_of(origin); | ||
if left_idx >= heap.len() { | ||
return; | ||
} | ||
|
||
let replacement_idx = | ||
if right_idx < heap.len() && is_less_than(&heap[left_idx], &heap[right_idx]) { | ||
right_idx | ||
} else { | ||
left_idx | ||
}; | ||
|
||
if is_less_than(&heap[origin], &heap[replacement_idx]) { | ||
heap.swap(origin, replacement_idx); | ||
origin = replacement_idx; | ||
} else { | ||
return; | ||
} | ||
} | ||
} | ||
|
||
pub(crate) fn k_smallest<T: Ord, I: Iterator<Item = T>>(mut iter: I, k: usize) -> BinaryHeap<T> { | ||
if k == 0 { | ||
return BinaryHeap::new(); | ||
return Vec::new(); | ||
} | ||
let mut storage: Vec<I::Item> = iter.by_ref().take(k).collect(); | ||
|
||
let mut heap = iter.by_ref().take(k).collect::<BinaryHeap<_>>(); | ||
let mut is_less_than = move |a: &_, b: &_| comparator(a, b) == Ordering::Less; | ||
|
||
iter.for_each(|i| { | ||
debug_assert_eq!(heap.len(), k); | ||
// Equivalent to heap.push(min(i, heap.pop())) but more efficient. | ||
// This should be done with a single `.peek_mut().unwrap()` but | ||
// `PeekMut` sifts-down unconditionally on Rust 1.46.0 and prior. | ||
if *heap.peek().unwrap() > i { | ||
*heap.peek_mut().unwrap() = i; | ||
} | ||
}); | ||
// Rearrange the storage into a valid heap by reordering from the second-bottom-most layer up to the root. | ||
// Slightly faster than ordering on each insert, but only by a factor of lg(k). | ||
// The resulting heap has the **largest** item on top. | ||
for i in (0..=(storage.len() / 2)).rev() { | ||
sift_down(&mut storage, &mut is_less_than, i); | ||
} | ||
|
||
if k == storage.len() { | ||
// If we fill the storage, there may still be iterator elements left so feed them into the heap. | ||
// Also avoids unexpected behaviour with restartable iterators. | ||
iter.for_each(|val| { | ||
if is_less_than(&val, &storage[0]) { | ||
// Treating this as an push-and-pop saves having to write a sift-up implementation. | ||
// https://en.wikipedia.org/wiki/Binary_heap#Insert_then_extract | ||
storage[0] = val; | ||
// We retain the smallest items we've seen so far, but ordered largest first so we can drop the largest efficiently. | ||
sift_down(&mut storage, &mut is_less_than, 0); | ||
} | ||
}); | ||
} | ||
|
||
// Ultimately the items need to be in least-first, strict order, but the heap is currently largest-first. | ||
// To achieve this, repeatedly, | ||
// 1) "pop" the largest item off the heap into the tail slot of the underlying storage, | ||
// 2) shrink the logical size of the heap by 1, | ||
// 3) restore the heap property over the remaining items. | ||
let mut heap = &mut storage[..]; | ||
while heap.len() > 1 { | ||
let last_idx = heap.len() - 1; | ||
heap.swap(0, last_idx); | ||
// Sifting over a truncated slice means that the sifting will not disturb already popped elements. | ||
heap = &mut heap[..last_idx]; | ||
sift_down(heap, &mut is_less_than, 0); | ||
} | ||
|
||
storage | ||
} | ||
|
||
heap | ||
#[inline] | ||
pub(crate) fn key_to_cmp<T, K, F>(key: F) -> impl Fn(&T, &T) -> Ordering | ||
Philippe-Cholet marked this conversation as resolved.
Show resolved
Hide resolved
|
||
where | ||
F: Fn(&T) -> K, | ||
K: Ord, | ||
{ | ||
move |a, b| key(a).cmp(&key(b)) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.