1 //! A priority queue implemented with a binary heap.
3 //! Insertion and popping the largest element have *O*(log(*n*)) time complexity.
4 //! Checking the largest element is *O*(1). Converting a vector to a binary heap
5 //! can be done in-place, and has *O*(*n*) complexity. A binary heap can also be
6 //! converted to a sorted vector in-place, allowing it to be used for an *O*(*n* * log(*n*))
11 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
12 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
13 //! It shows how to use [`BinaryHeap`] with custom types.
15 //! [dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
16 //! [sssp]: https://en.wikipedia.org/wiki/Shortest_path_problem
17 //! [dir_graph]: https://en.wikipedia.org/wiki/Directed_graph
20 //! use std::cmp::Ordering;
21 //! use std::collections::BinaryHeap;
23 //! #[derive(Copy, Clone, Eq, PartialEq)]
29 //! // The priority queue depends on `Ord`.
30 //! // Explicitly implement the trait so the queue becomes a min-heap
31 //! // instead of a max-heap.
32 //! impl Ord for State {
33 //! fn cmp(&self, other: &Self) -> Ordering {
34 //! // Notice that the we flip the ordering on costs.
35 //! // In case of a tie we compare positions - this step is necessary
36 //! // to make implementations of `PartialEq` and `Ord` consistent.
37 //! other.cost.cmp(&self.cost)
38 //! .then_with(|| self.position.cmp(&other.position))
42 //! // `PartialOrd` needs to be implemented as well.
43 //! impl PartialOrd for State {
44 //! fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
45 //! Some(self.cmp(other))
49 //! // Each node is represented as a `usize`, for a shorter implementation.
55 //! // Dijkstra's shortest path algorithm.
57 //! // Start at `start` and use `dist` to track the current shortest distance
58 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
59 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
60 //! // for a simpler implementation.
61 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
62 //! // dist[node] = current shortest distance from `start` to `node`
63 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
65 //! let mut heap = BinaryHeap::new();
67 //! // We're at `start`, with a zero cost
69 //! heap.push(State { cost: 0, position: start });
71 //! // Examine the frontier with lower cost nodes first (min-heap)
72 //! while let Some(State { cost, position }) = heap.pop() {
73 //! // Alternatively we could have continued to find all shortest paths
74 //! if position == goal { return Some(cost); }
76 //! // Important as we may have already found a better way
77 //! if cost > dist[position] { continue; }
79 //! // For each node we can reach, see if we can find a way with
80 //! // a lower cost going through this node
81 //! for edge in &adj_list[position] {
82 //! let next = State { cost: cost + edge.cost, position: edge.node };
84 //! // If so, add it to the frontier and continue
85 //! if next.cost < dist[next.position] {
87 //! // Relaxation, we have now found a better way
88 //! dist[next.position] = next.cost;
93 //! // Goal not reachable
98 //! // This is the directed graph we're going to use.
99 //! // The node numbers correspond to the different states,
100 //! // and the edge weights symbolize the cost of moving
101 //! // from one node to another.
102 //! // Note that the edges are one-way.
105 //! // +-----------------+
108 //! // 0 -----> 1 -----> 3 ---> 4
112 //! // +------> 2 -------+ |
114 //! // +---------------+
116 //! // The graph is represented as an adjacency list where each index,
117 //! // corresponding to a node value, has a list of outgoing edges.
118 //! // Chosen for its efficiency.
119 //! let graph = vec![
121 //! vec![Edge { node: 2, cost: 10 },
122 //! Edge { node: 1, cost: 1 }],
124 //! vec![Edge { node: 3, cost: 2 }],
126 //! vec![Edge { node: 1, cost: 1 },
127 //! Edge { node: 3, cost: 3 },
128 //! Edge { node: 4, cost: 1 }],
130 //! vec![Edge { node: 0, cost: 7 },
131 //! Edge { node: 4, cost: 2 }],
135 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
136 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
137 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
138 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
139 //! assert_eq!(shortest_path(&graph, 4, 0), None);
143 #![allow(missing_docs)]
144 #![stable(feature = "rust1", since = "1.0.0")]
147 use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
148 use core::mem::{self, swap, ManuallyDrop};
149 use core::ops::{Deref, DerefMut};
153 use crate::vec::{self, AsIntoIter, Vec};
155 use super::SpecExtend;
157 /// A priority queue implemented with a binary heap.
159 /// This will be a max-heap.
161 /// It is a logic error for an item to be modified in such a way that the
162 /// item's ordering relative to any other item, as determined by the [`Ord`]
163 /// trait, changes while it is in the heap. This is normally only possible
164 /// through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. The
165 /// behavior resulting from such a logic error is not specified (it
166 /// could include panics, incorrect results, aborts, memory leaks, or
167 /// non-termination) but will not be undefined behavior.
172 /// use std::collections::BinaryHeap;
174 /// // Type inference lets us omit an explicit type signature (which
175 /// // would be `BinaryHeap<i32>` in this example).
176 /// let mut heap = BinaryHeap::new();
178 /// // We can use peek to look at the next item in the heap. In this case,
179 /// // there's no items in there yet so we get None.
180 /// assert_eq!(heap.peek(), None);
182 /// // Let's add some scores...
187 /// // Now peek shows the most important item in the heap.
188 /// assert_eq!(heap.peek(), Some(&5));
190 /// // We can check the length of a heap.
191 /// assert_eq!(heap.len(), 3);
193 /// // We can iterate over the items in the heap, although they are returned in
194 /// // a random order.
196 /// println!("{}", x);
199 /// // If we instead pop these scores, they should come back in order.
200 /// assert_eq!(heap.pop(), Some(5));
201 /// assert_eq!(heap.pop(), Some(2));
202 /// assert_eq!(heap.pop(), Some(1));
203 /// assert_eq!(heap.pop(), None);
205 /// // We can clear the heap of any remaining items.
208 /// // The heap should now be empty.
209 /// assert!(heap.is_empty())
212 /// A `BinaryHeap` with a known list of items can be initialized from an array:
215 /// use std::collections::BinaryHeap;
217 /// let heap = BinaryHeap::from([1, 5, 2]);
222 /// Either [`core::cmp::Reverse`] or a custom [`Ord`] implementation can be used to
223 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
224 /// value instead of the greatest one.
227 /// use std::collections::BinaryHeap;
228 /// use std::cmp::Reverse;
230 /// let mut heap = BinaryHeap::new();
232 /// // Wrap values in `Reverse`
233 /// heap.push(Reverse(1));
234 /// heap.push(Reverse(5));
235 /// heap.push(Reverse(2));
237 /// // If we pop these scores now, they should come back in the reverse order.
238 /// assert_eq!(heap.pop(), Some(Reverse(1)));
239 /// assert_eq!(heap.pop(), Some(Reverse(2)));
240 /// assert_eq!(heap.pop(), Some(Reverse(5)));
241 /// assert_eq!(heap.pop(), None);
244 /// # Time complexity
246 /// | [push] | [pop] | [peek]/[peek\_mut] |
247 /// |---------|---------------|--------------------|
248 /// | *O*(1)~ | *O*(log(*n*)) | *O*(1) |
250 /// The value for `push` is an expected cost; the method documentation gives a
251 /// more detailed analysis.
253 /// [`core::cmp::Reverse`]: core::cmp::Reverse
254 /// [`Ord`]: core::cmp::Ord
255 /// [`Cell`]: core::cell::Cell
256 /// [`RefCell`]: core::cell::RefCell
257 /// [push]: BinaryHeap::push
258 /// [pop]: BinaryHeap::pop
259 /// [peek]: BinaryHeap::peek
260 /// [peek\_mut]: BinaryHeap::peek_mut
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
263 pub struct BinaryHeap<T> {
267 /// Structure wrapping a mutable reference to the greatest item on a
270 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
271 /// its documentation for more.
273 /// [`peek_mut`]: BinaryHeap::peek_mut
274 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
275 pub struct PeekMut<'a, T: 'a + Ord> {
276 heap: &'a mut BinaryHeap<T>,
280 #[stable(feature = "collection_debug", since = "1.17.0")]
281 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
287 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
288 impl<T: Ord> Drop for PeekMut<'_, T> {
291 // SAFETY: PeekMut is only instantiated for non-empty heaps.
292 unsafe { self.heap.sift_down(0) };
297 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
298 impl<T: Ord> Deref for PeekMut<'_, T> {
300 fn deref(&self) -> &T {
301 debug_assert!(!self.heap.is_empty());
302 // SAFE: PeekMut is only instantiated for non-empty heaps
303 unsafe { self.heap.data.get_unchecked(0) }
307 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
308 impl<T: Ord> DerefMut for PeekMut<'_, T> {
309 fn deref_mut(&mut self) -> &mut T {
310 debug_assert!(!self.heap.is_empty());
312 // SAFE: PeekMut is only instantiated for non-empty heaps
313 unsafe { self.heap.data.get_unchecked_mut(0) }
317 impl<'a, T: Ord> PeekMut<'a, T> {
318 /// Removes the peeked value from the heap and returns it.
319 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
320 pub fn pop(mut this: PeekMut<'a, T>) -> T {
321 let value = this.heap.pop().unwrap();
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl<T: Clone> Clone for BinaryHeap<T> {
329 fn clone(&self) -> Self {
330 BinaryHeap { data: self.data.clone() }
333 fn clone_from(&mut self, source: &Self) {
334 self.data.clone_from(&source.data);
338 #[stable(feature = "rust1", since = "1.0.0")]
339 impl<T: Ord> Default for BinaryHeap<T> {
340 /// Creates an empty `BinaryHeap<T>`.
342 fn default() -> BinaryHeap<T> {
347 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
348 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 f.debug_list().entries(self.iter()).finish()
354 impl<T: Ord> BinaryHeap<T> {
355 /// Creates an empty `BinaryHeap` as a max-heap.
362 /// use std::collections::BinaryHeap;
363 /// let mut heap = BinaryHeap::new();
366 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn new() -> BinaryHeap<T> {
369 BinaryHeap { data: vec![] }
372 /// Creates an empty `BinaryHeap` with a specific capacity.
373 /// This preallocates enough memory for `capacity` elements,
374 /// so that the `BinaryHeap` does not have to be reallocated
375 /// until it contains at least that many values.
382 /// use std::collections::BinaryHeap;
383 /// let mut heap = BinaryHeap::with_capacity(10);
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
389 BinaryHeap { data: Vec::with_capacity(capacity) }
392 /// Returns a mutable reference to the greatest item in the binary heap, or
393 /// `None` if it is empty.
395 /// Note: If the `PeekMut` value is leaked, the heap may be in an
396 /// inconsistent state.
403 /// use std::collections::BinaryHeap;
404 /// let mut heap = BinaryHeap::new();
405 /// assert!(heap.peek_mut().is_none());
411 /// let mut val = heap.peek_mut().unwrap();
414 /// assert_eq!(heap.peek(), Some(&2));
417 /// # Time complexity
419 /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
420 /// otherwise it's *O*(1).
421 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
422 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
423 if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: false }) }
426 /// Removes the greatest item from the binary heap and returns it, or `None` if it
434 /// use std::collections::BinaryHeap;
435 /// let mut heap = BinaryHeap::from(vec![1, 3]);
437 /// assert_eq!(heap.pop(), Some(3));
438 /// assert_eq!(heap.pop(), Some(1));
439 /// assert_eq!(heap.pop(), None);
442 /// # Time complexity
444 /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn pop(&mut self) -> Option<T> {
447 self.data.pop().map(|mut item| {
448 if !self.is_empty() {
449 swap(&mut item, &mut self.data[0]);
450 // SAFETY: !self.is_empty() means that self.len() > 0
451 unsafe { self.sift_down_to_bottom(0) };
457 /// Pushes an item onto the binary heap.
464 /// use std::collections::BinaryHeap;
465 /// let mut heap = BinaryHeap::new();
470 /// assert_eq!(heap.len(), 3);
471 /// assert_eq!(heap.peek(), Some(&5));
474 /// # Time complexity
476 /// The expected cost of `push`, averaged over every possible ordering of
477 /// the elements being pushed, and over a sufficiently large number of
478 /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
479 /// elements that are *not* already in any sorted pattern.
481 /// The time complexity degrades if elements are pushed in predominantly
482 /// ascending order. In the worst case, elements are pushed in ascending
483 /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
484 /// containing *n* elements.
486 /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
487 /// occurs when capacity is exhausted and needs a resize. The resize cost
488 /// has been amortized in the previous figures.
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn push(&mut self, item: T) {
491 let old_len = self.len();
492 self.data.push(item);
493 // SAFETY: Since we pushed a new item it means that
494 // old_len = self.len() - 1 < self.len()
495 unsafe { self.sift_up(0, old_len) };
498 /// Consumes the `BinaryHeap` and returns a vector in sorted
499 /// (ascending) order.
506 /// use std::collections::BinaryHeap;
508 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
512 /// let vec = heap.into_sorted_vec();
513 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
515 #[must_use = "`self` will be dropped if the result is not used"]
516 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
517 pub fn into_sorted_vec(mut self) -> Vec<T> {
518 let mut end = self.len();
521 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
522 // so it's always a valid index to access.
523 // It is safe to access index 0 (i.e. `ptr`), because
524 // 1 <= end < self.len(), which means self.len() >= 2.
526 let ptr = self.data.as_mut_ptr();
527 ptr::swap(ptr, ptr.add(end));
529 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
530 // 0 < 1 <= end <= self.len() - 1 < self.len()
531 // Which means 0 < end and end < self.len().
532 unsafe { self.sift_down_range(0, end) };
537 // The implementations of sift_up and sift_down use unsafe blocks in
538 // order to move an element out of the vector (leaving behind a
539 // hole), shift along the others and move the removed element back into the
540 // vector at the final location of the hole.
541 // The `Hole` type is used to represent this, and make sure
542 // the hole is filled back at the end of its scope, even on panic.
543 // Using a hole reduces the constant factor compared to using swaps,
544 // which involves twice as many moves.
548 /// The caller must guarantee that `pos < self.len()`.
549 unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
550 // Take out the value at `pos` and create a hole.
551 // SAFETY: The caller guarantees that pos < self.len()
552 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
554 while hole.pos() > start {
555 let parent = (hole.pos() - 1) / 2;
557 // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
558 // and so hole.pos() - 1 can't underflow.
559 // This guarantees that parent < hole.pos() so
560 // it's a valid index and also != hole.pos().
561 if hole.element() <= unsafe { hole.get(parent) } {
565 // SAFETY: Same as above
566 unsafe { hole.move_to(parent) };
572 /// Take an element at `pos` and move it down the heap,
573 /// while its children are larger.
577 /// The caller must guarantee that `pos < end <= self.len()`.
578 unsafe fn sift_down_range(&mut self, pos: usize, end: usize) {
579 // SAFETY: The caller guarantees that pos < end <= self.len().
580 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
581 let mut child = 2 * hole.pos() + 1;
583 // Loop invariant: child == 2 * hole.pos() + 1.
584 while child <= end.saturating_sub(2) {
585 // compare with the greater of the two children
586 // SAFETY: child < end - 1 < self.len() and
587 // child + 1 < end <= self.len(), so they're valid indexes.
588 // child == 2 * hole.pos() + 1 != hole.pos() and
589 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
590 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
592 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
594 // if we are already in order, stop.
595 // SAFETY: child is now either the old child or the old child+1
596 // We already proven that both are < self.len() and != hole.pos()
597 if hole.element() >= unsafe { hole.get(child) } {
601 // SAFETY: same as above.
602 unsafe { hole.move_to(child) };
603 child = 2 * hole.pos() + 1;
606 // SAFETY: && short circuit, which means that in the
607 // second condition it's already true that child == end - 1 < self.len().
608 if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
609 // SAFETY: child is already proven to be a valid index and
610 // child == 2 * hole.pos() + 1 != hole.pos().
611 unsafe { hole.move_to(child) };
617 /// The caller must guarantee that `pos < self.len()`.
618 unsafe fn sift_down(&mut self, pos: usize) {
619 let len = self.len();
620 // SAFETY: pos < len is guaranteed by the caller and
621 // obviously len = self.len() <= self.len().
622 unsafe { self.sift_down_range(pos, len) };
625 /// Take an element at `pos` and move it all the way down the heap,
626 /// then sift it up to its position.
628 /// Note: This is faster when the element is known to be large / should
629 /// be closer to the bottom.
633 /// The caller must guarantee that `pos < self.len()`.
634 unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
635 let end = self.len();
638 // SAFETY: The caller guarantees that pos < self.len().
639 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
640 let mut child = 2 * hole.pos() + 1;
642 // Loop invariant: child == 2 * hole.pos() + 1.
643 while child <= end.saturating_sub(2) {
644 // SAFETY: child < end - 1 < self.len() and
645 // child + 1 < end <= self.len(), so they're valid indexes.
646 // child == 2 * hole.pos() + 1 != hole.pos() and
647 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
648 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
650 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
652 // SAFETY: Same as above
653 unsafe { hole.move_to(child) };
654 child = 2 * hole.pos() + 1;
657 if child == end - 1 {
658 // SAFETY: child == end - 1 < self.len(), so it's a valid index
659 // and child == 2 * hole.pos() + 1 != hole.pos().
660 unsafe { hole.move_to(child) };
665 // SAFETY: pos is the position in the hole and was already proven
666 // to be a valid index.
667 unsafe { self.sift_up(start, pos) };
670 /// Rebuild assuming data[0..start] is still a proper heap.
671 fn rebuild_tail(&mut self, start: usize) {
672 if start == self.len() {
676 let tail_len = self.len() - start;
679 fn log2_fast(x: usize) -> usize {
680 (usize::BITS - x.leading_zeros() - 1) as usize
683 // `rebuild` takes O(self.len()) operations
684 // and about 2 * self.len() comparisons in the worst case
685 // while repeating `sift_up` takes O(tail_len * log(start)) operations
686 // and about 1 * tail_len * log_2(start) comparisons in the worst case,
687 // assuming start >= tail_len. For larger heaps, the crossover point
688 // no longer follows this reasoning and was determined empirically.
689 let better_to_rebuild = if start < tail_len {
691 } else if self.len() <= 2048 {
692 2 * self.len() < tail_len * log2_fast(start)
694 2 * self.len() < tail_len * 11
697 if better_to_rebuild {
700 for i in start..self.len() {
701 // SAFETY: The index `i` is always less than self.len().
702 unsafe { self.sift_up(0, i) };
707 fn rebuild(&mut self) {
708 let mut n = self.len() / 2;
711 // SAFETY: n starts from self.len() / 2 and goes down to 0.
712 // The only case when !(n < self.len()) is if
713 // self.len() == 0, but it's ruled out by the loop condition.
714 unsafe { self.sift_down(n) };
718 /// Moves all the elements of `other` into `self`, leaving `other` empty.
725 /// use std::collections::BinaryHeap;
727 /// let v = vec![-10, 1, 2, 3, 3];
728 /// let mut a = BinaryHeap::from(v);
730 /// let v = vec![-20, 5, 43];
731 /// let mut b = BinaryHeap::from(v);
733 /// a.append(&mut b);
735 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
736 /// assert!(b.is_empty());
738 #[stable(feature = "binary_heap_append", since = "1.11.0")]
739 pub fn append(&mut self, other: &mut Self) {
740 if self.len() < other.len() {
744 let start = self.data.len();
746 self.data.append(&mut other.data);
748 self.rebuild_tail(start);
751 /// Returns an iterator which retrieves elements in heap order.
752 /// The retrieved elements are removed from the original heap.
753 /// The remaining elements will be removed on drop in heap order.
756 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
757 /// You should use the latter for most cases.
764 /// #![feature(binary_heap_drain_sorted)]
765 /// use std::collections::BinaryHeap;
767 /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
768 /// assert_eq!(heap.len(), 5);
770 /// drop(heap.drain_sorted()); // removes all elements in heap order
771 /// assert_eq!(heap.len(), 0);
774 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
775 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
776 DrainSorted { inner: self }
779 /// Retains only the elements specified by the predicate.
781 /// In other words, remove all elements `e` such that `f(&e)` returns
782 /// `false`. The elements are visited in unsorted (and unspecified) order.
789 /// #![feature(binary_heap_retain)]
790 /// use std::collections::BinaryHeap;
792 /// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
794 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
796 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
798 #[unstable(feature = "binary_heap_retain", issue = "71503")]
799 pub fn retain<F>(&mut self, mut f: F)
801 F: FnMut(&T) -> bool,
803 let mut first_removed = self.len();
805 self.data.retain(|e| {
807 if !keep && i < first_removed {
813 // data[0..first_removed] is untouched, so we only need to rebuild the tail:
814 self.rebuild_tail(first_removed);
818 impl<T> BinaryHeap<T> {
819 /// Returns an iterator visiting all values in the underlying vector, in
827 /// use std::collections::BinaryHeap;
828 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
830 /// // Print 1, 2, 3, 4 in arbitrary order
831 /// for x in heap.iter() {
832 /// println!("{}", x);
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn iter(&self) -> Iter<'_, T> {
837 Iter { iter: self.data.iter() }
840 /// Returns an iterator which retrieves elements in heap order.
841 /// This method consumes the original heap.
848 /// #![feature(binary_heap_into_iter_sorted)]
849 /// use std::collections::BinaryHeap;
850 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
852 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]);
854 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
855 pub fn into_iter_sorted(self) -> IntoIterSorted<T> {
856 IntoIterSorted { inner: self }
859 /// Returns the greatest item in the binary heap, or `None` if it is empty.
866 /// use std::collections::BinaryHeap;
867 /// let mut heap = BinaryHeap::new();
868 /// assert_eq!(heap.peek(), None);
873 /// assert_eq!(heap.peek(), Some(&5));
877 /// # Time complexity
879 /// Cost is *O*(1) in the worst case.
881 #[stable(feature = "rust1", since = "1.0.0")]
882 pub fn peek(&self) -> Option<&T> {
886 /// Returns the number of elements the binary heap can hold without reallocating.
893 /// use std::collections::BinaryHeap;
894 /// let mut heap = BinaryHeap::with_capacity(100);
895 /// assert!(heap.capacity() >= 100);
899 #[stable(feature = "rust1", since = "1.0.0")]
900 pub fn capacity(&self) -> usize {
904 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
905 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
907 /// Note that the allocator may give the collection more space than it requests. Therefore
908 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
909 /// insertions are expected.
913 /// Panics if the new capacity overflows `usize`.
920 /// use std::collections::BinaryHeap;
921 /// let mut heap = BinaryHeap::new();
922 /// heap.reserve_exact(100);
923 /// assert!(heap.capacity() >= 100);
927 /// [`reserve`]: BinaryHeap::reserve
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn reserve_exact(&mut self, additional: usize) {
930 self.data.reserve_exact(additional);
933 /// Reserves capacity for at least `additional` more elements to be inserted in the
934 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
938 /// Panics if the new capacity overflows `usize`.
945 /// use std::collections::BinaryHeap;
946 /// let mut heap = BinaryHeap::new();
947 /// heap.reserve(100);
948 /// assert!(heap.capacity() >= 100);
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn reserve(&mut self, additional: usize) {
953 self.data.reserve(additional);
956 /// Discards as much additional capacity as possible.
963 /// use std::collections::BinaryHeap;
964 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
966 /// assert!(heap.capacity() >= 100);
967 /// heap.shrink_to_fit();
968 /// assert!(heap.capacity() == 0);
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn shrink_to_fit(&mut self) {
972 self.data.shrink_to_fit();
975 /// Discards capacity with a lower bound.
977 /// The capacity will remain at least as large as both the length
978 /// and the supplied value.
980 /// If the current capacity is less than the lower limit, this is a no-op.
985 /// use std::collections::BinaryHeap;
986 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
988 /// assert!(heap.capacity() >= 100);
989 /// heap.shrink_to(10);
990 /// assert!(heap.capacity() >= 10);
993 #[stable(feature = "shrink_to", since = "1.56.0")]
994 pub fn shrink_to(&mut self, min_capacity: usize) {
995 self.data.shrink_to(min_capacity)
998 /// Returns a slice of all values in the underlying vector, in arbitrary
1006 /// #![feature(binary_heap_as_slice)]
1007 /// use std::collections::BinaryHeap;
1008 /// use std::io::{self, Write};
1010 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
1012 /// io::sink().write(heap.as_slice()).unwrap();
1015 #[unstable(feature = "binary_heap_as_slice", issue = "83659")]
1016 pub fn as_slice(&self) -> &[T] {
1017 self.data.as_slice()
1020 /// Consumes the `BinaryHeap` and returns the underlying vector
1021 /// in arbitrary order.
1028 /// use std::collections::BinaryHeap;
1029 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
1030 /// let vec = heap.into_vec();
1032 /// // Will print in some order
1034 /// println!("{}", x);
1037 #[must_use = "`self` will be dropped if the result is not used"]
1038 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1039 pub fn into_vec(self) -> Vec<T> {
1043 /// Returns the length of the binary heap.
1050 /// use std::collections::BinaryHeap;
1051 /// let heap = BinaryHeap::from(vec![1, 3]);
1053 /// assert_eq!(heap.len(), 2);
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 pub fn len(&self) -> usize {
1061 /// Checks if the binary heap is empty.
1068 /// use std::collections::BinaryHeap;
1069 /// let mut heap = BinaryHeap::new();
1071 /// assert!(heap.is_empty());
1077 /// assert!(!heap.is_empty());
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 pub fn is_empty(&self) -> bool {
1085 /// Clears the binary heap, returning an iterator over the removed elements.
1087 /// The elements are removed in arbitrary order.
1094 /// use std::collections::BinaryHeap;
1095 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1097 /// assert!(!heap.is_empty());
1099 /// for x in heap.drain() {
1100 /// println!("{}", x);
1103 /// assert!(heap.is_empty());
1106 #[stable(feature = "drain", since = "1.6.0")]
1107 pub fn drain(&mut self) -> Drain<'_, T> {
1108 Drain { iter: self.data.drain(..) }
1111 /// Drops all items from the binary heap.
1118 /// use std::collections::BinaryHeap;
1119 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1121 /// assert!(!heap.is_empty());
1125 /// assert!(heap.is_empty());
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn clear(&mut self) {
1133 /// Hole represents a hole in a slice i.e., an index without valid value
1134 /// (because it was moved from or duplicated).
1135 /// In drop, `Hole` will restore the slice by filling the hole
1136 /// position with the value that was originally removed.
1137 struct Hole<'a, T: 'a> {
1139 elt: ManuallyDrop<T>,
1143 impl<'a, T> Hole<'a, T> {
1144 /// Create a new `Hole` at index `pos`.
1146 /// Unsafe because pos must be within the data slice.
1148 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1149 debug_assert!(pos < data.len());
1150 // SAFE: pos should be inside the slice
1151 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1152 Hole { data, elt: ManuallyDrop::new(elt), pos }
1156 fn pos(&self) -> usize {
1160 /// Returns a reference to the element removed.
1162 fn element(&self) -> &T {
1166 /// Returns a reference to the element at `index`.
1168 /// Unsafe because index must be within the data slice and not equal to pos.
1170 unsafe fn get(&self, index: usize) -> &T {
1171 debug_assert!(index != self.pos);
1172 debug_assert!(index < self.data.len());
1173 unsafe { self.data.get_unchecked(index) }
1176 /// Move hole to new location
1178 /// Unsafe because index must be within the data slice and not equal to pos.
1180 unsafe fn move_to(&mut self, index: usize) {
1181 debug_assert!(index != self.pos);
1182 debug_assert!(index < self.data.len());
1184 let ptr = self.data.as_mut_ptr();
1185 let index_ptr: *const _ = ptr.add(index);
1186 let hole_ptr = ptr.add(self.pos);
1187 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1193 impl<T> Drop for Hole<'_, T> {
1195 fn drop(&mut self) {
1196 // fill the hole again
1199 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1204 /// An iterator over the elements of a `BinaryHeap`.
1206 /// This `struct` is created by [`BinaryHeap::iter()`]. See its
1207 /// documentation for more.
1209 /// [`iter`]: BinaryHeap::iter
1210 #[must_use = "iterators are lazy and do nothing unless consumed"]
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub struct Iter<'a, T: 'a> {
1213 iter: slice::Iter<'a, T>,
1216 #[stable(feature = "collection_debug", since = "1.17.0")]
1217 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1223 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 impl<T> Clone for Iter<'_, T> {
1226 fn clone(&self) -> Self {
1227 Iter { iter: self.iter.clone() }
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 impl<'a, T> Iterator for Iter<'a, T> {
1236 fn next(&mut self) -> Option<&'a T> {
1241 fn size_hint(&self) -> (usize, Option<usize>) {
1242 self.iter.size_hint()
1246 fn last(self) -> Option<&'a T> {
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1254 fn next_back(&mut self) -> Option<&'a T> {
1255 self.iter.next_back()
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 impl<T> ExactSizeIterator for Iter<'_, T> {
1261 fn is_empty(&self) -> bool {
1262 self.iter.is_empty()
1266 #[stable(feature = "fused", since = "1.26.0")]
1267 impl<T> FusedIterator for Iter<'_, T> {}
1269 /// An owning iterator over the elements of a `BinaryHeap`.
1271 /// This `struct` is created by [`BinaryHeap::into_iter()`]
1272 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1274 /// [`into_iter`]: BinaryHeap::into_iter
1275 /// [`IntoIterator`]: core::iter::IntoIterator
1276 #[stable(feature = "rust1", since = "1.0.0")]
1278 pub struct IntoIter<T> {
1279 iter: vec::IntoIter<T>,
1282 #[stable(feature = "collection_debug", since = "1.17.0")]
1283 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1285 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 impl<T> Iterator for IntoIter<T> {
1294 fn next(&mut self) -> Option<T> {
1299 fn size_hint(&self) -> (usize, Option<usize>) {
1300 self.iter.size_hint()
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T> DoubleEndedIterator for IntoIter<T> {
1307 fn next_back(&mut self) -> Option<T> {
1308 self.iter.next_back()
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<T> ExactSizeIterator for IntoIter<T> {
1314 fn is_empty(&self) -> bool {
1315 self.iter.is_empty()
1319 #[stable(feature = "fused", since = "1.26.0")]
1320 impl<T> FusedIterator for IntoIter<T> {}
1322 #[unstable(issue = "none", feature = "inplace_iteration")]
1324 unsafe impl<T> SourceIter for IntoIter<T> {
1325 type Source = IntoIter<T>;
1328 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1333 #[unstable(issue = "none", feature = "inplace_iteration")]
1335 unsafe impl<I> InPlaceIterable for IntoIter<I> {}
1337 impl<I> AsIntoIter for IntoIter<I> {
1340 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1345 #[must_use = "iterators are lazy and do nothing unless consumed"]
1346 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1347 #[derive(Clone, Debug)]
1348 pub struct IntoIterSorted<T> {
1349 inner: BinaryHeap<T>,
1352 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1353 impl<T: Ord> Iterator for IntoIterSorted<T> {
1357 fn next(&mut self) -> Option<T> {
1362 fn size_hint(&self) -> (usize, Option<usize>) {
1363 let exact = self.inner.len();
1364 (exact, Some(exact))
1368 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1369 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1371 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1372 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1374 #[unstable(feature = "trusted_len", issue = "37572")]
1375 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1377 /// A draining iterator over the elements of a `BinaryHeap`.
1379 /// This `struct` is created by [`BinaryHeap::drain()`]. See its
1380 /// documentation for more.
1382 /// [`drain`]: BinaryHeap::drain
1383 #[stable(feature = "drain", since = "1.6.0")]
1385 pub struct Drain<'a, T: 'a> {
1386 iter: vec::Drain<'a, T>,
1389 #[stable(feature = "drain", since = "1.6.0")]
1390 impl<T> Iterator for Drain<'_, T> {
1394 fn next(&mut self) -> Option<T> {
1399 fn size_hint(&self) -> (usize, Option<usize>) {
1400 self.iter.size_hint()
1404 #[stable(feature = "drain", since = "1.6.0")]
1405 impl<T> DoubleEndedIterator for Drain<'_, T> {
1407 fn next_back(&mut self) -> Option<T> {
1408 self.iter.next_back()
1412 #[stable(feature = "drain", since = "1.6.0")]
1413 impl<T> ExactSizeIterator for Drain<'_, T> {
1414 fn is_empty(&self) -> bool {
1415 self.iter.is_empty()
1419 #[stable(feature = "fused", since = "1.26.0")]
1420 impl<T> FusedIterator for Drain<'_, T> {}
1422 /// A draining iterator over the elements of a `BinaryHeap`.
1424 /// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1425 /// documentation for more.
1427 /// [`drain_sorted`]: BinaryHeap::drain_sorted
1428 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1430 pub struct DrainSorted<'a, T: Ord> {
1431 inner: &'a mut BinaryHeap<T>,
1434 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1435 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1436 /// Removes heap elements in heap order.
1437 fn drop(&mut self) {
1438 struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1440 impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1441 fn drop(&mut self) {
1442 while self.0.inner.pop().is_some() {}
1446 while let Some(item) = self.inner.pop() {
1447 let guard = DropGuard(self);
1454 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1455 impl<T: Ord> Iterator for DrainSorted<'_, T> {
1459 fn next(&mut self) -> Option<T> {
1464 fn size_hint(&self) -> (usize, Option<usize>) {
1465 let exact = self.inner.len();
1466 (exact, Some(exact))
1470 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1471 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1473 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1474 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1476 #[unstable(feature = "trusted_len", issue = "37572")]
1477 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1479 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1480 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1481 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1483 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1484 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1485 let mut heap = BinaryHeap { data: vec };
1491 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1492 impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1494 /// use std::collections::BinaryHeap;
1496 /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1497 /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1498 /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1499 /// assert_eq!(a, b);
1502 fn from(arr: [T; N]) -> Self {
1503 core::array::IntoIter::new(arr).collect()
1507 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1508 impl<T> From<BinaryHeap<T>> for Vec<T> {
1509 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1511 /// This conversion requires no data movement or allocation, and has
1512 /// constant time complexity.
1513 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1520 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1521 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl<T> IntoIterator for BinaryHeap<T> {
1528 type IntoIter = IntoIter<T>;
1530 /// Creates a consuming iterator, that is, one that moves each value out of
1531 /// the binary heap in arbitrary order. The binary heap cannot be used
1532 /// after calling this.
1539 /// use std::collections::BinaryHeap;
1540 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1542 /// // Print 1, 2, 3, 4 in arbitrary order
1543 /// for x in heap.into_iter() {
1544 /// // x has type i32, not &i32
1545 /// println!("{}", x);
1548 fn into_iter(self) -> IntoIter<T> {
1549 IntoIter { iter: self.data.into_iter() }
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1556 type IntoIter = Iter<'a, T>;
1558 fn into_iter(self) -> Iter<'a, T> {
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1566 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1567 <Self as SpecExtend<I>>::spec_extend(self, iter);
1571 fn extend_one(&mut self, item: T) {
1576 fn extend_reserve(&mut self, additional: usize) {
1577 self.reserve(additional);
1581 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1582 default fn spec_extend(&mut self, iter: I) {
1583 self.extend_desugared(iter.into_iter());
1587 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1588 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1593 impl<T: Ord> BinaryHeap<T> {
1594 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1595 let iterator = iter.into_iter();
1596 let (lower, _) = iterator.size_hint();
1598 self.reserve(lower);
1600 iterator.for_each(move |elem| self.push(elem));
1604 #[stable(feature = "extend_ref", since = "1.2.0")]
1605 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1606 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1607 self.extend(iter.into_iter().cloned());
1611 fn extend_one(&mut self, &item: &'a T) {
1616 fn extend_reserve(&mut self, additional: usize) {
1617 self.reserve(additional);