1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A priority queue implemented with a binary heap.
13 //! Insertion and popping the largest element have `O(log n)` time complexity. Checking the largest
14 //! element is `O(1)`. Converting a vector to a binary heap can be done in-place, and has `O(n)`
15 //! complexity. A binary heap can also be converted to a sorted vector in-place, allowing it to
16 //! be used for an `O(n log n)` in-place heapsort.
20 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
21 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
22 //! It shows how to use `BinaryHeap` with custom types.
24 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
25 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
26 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
29 //! use std::cmp::Ordering;
30 //! use std::collections::BinaryHeap;
33 //! #[derive(Copy, Clone, Eq, PartialEq)]
39 //! // The priority queue depends on `Ord`.
40 //! // Explicitly implement the trait so the queue becomes a min-heap
41 //! // instead of a max-heap.
42 //! impl Ord for State {
43 //! fn cmp(&self, other: &State) -> Ordering {
44 //! // Notice that the we flip the ordering here
45 //! other.cost.cmp(&self.cost)
49 //! // `PartialOrd` needs to be implemented as well.
50 //! impl PartialOrd for State {
51 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
52 //! Some(self.cmp(other))
56 //! // Each node is represented as an `usize`, for a shorter implementation.
62 //! // Dijkstra's shortest path algorithm.
64 //! // Start at `start` and use `dist` to track the current shortest distance
65 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
66 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
67 //! // for a simpler implementation.
68 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize {
69 //! // dist[node] = current shortest distance from `start` to `node`
70 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
72 //! let mut heap = BinaryHeap::new();
74 //! // We're at `start`, with a zero cost
76 //! heap.push(State { cost: 0, position: start });
78 //! // Examine the frontier with lower cost nodes first (min-heap)
79 //! while let Some(State { cost, position }) = heap.pop() {
80 //! // Alternatively we could have continued to find all shortest paths
81 //! if position == goal { return cost; }
83 //! // Important as we may have already found a better way
84 //! if cost > dist[position] { continue; }
86 //! // For each node we can reach, see if we can find a way with
87 //! // a lower cost going through this node
88 //! for edge in adj_list[position].iter() {
89 //! let next = State { cost: cost + edge.cost, position: edge.node };
91 //! // If so, add it to the frontier and continue
92 //! if next.cost < dist[next.position] {
94 //! // Relaxation, we have now found a better way
95 //! dist[next.position] = next.cost;
100 //! // Goal not reachable
105 //! // This is the directed graph we're going to use.
106 //! // The node numbers correspond to the different states,
107 //! // and the edge weights symbolize the cost of moving
108 //! // from one node to another.
109 //! // Note that the edges are one-way.
112 //! // +-----------------+
115 //! // 0 -----> 1 -----> 3 ---> 4
119 //! // +------> 2 -------+ |
121 //! // +---------------+
123 //! // The graph is represented as an adjacency list where each index,
124 //! // corresponding to a node value, has a list of outgoing edges.
125 //! // Chosen for its efficiency.
126 //! let graph = vec![
128 //! vec![Edge { node: 2, cost: 10 },
129 //! Edge { node: 1, cost: 1 }],
131 //! vec![Edge { node: 3, cost: 2 }],
133 //! vec![Edge { node: 1, cost: 1 },
134 //! Edge { node: 3, cost: 3 },
135 //! Edge { node: 4, cost: 1 }],
137 //! vec![Edge { node: 0, cost: 7 },
138 //! Edge { node: 4, cost: 2 }],
142 //! assert_eq!(shortest_path(&graph, 0, 1), 1);
143 //! assert_eq!(shortest_path(&graph, 0, 3), 3);
144 //! assert_eq!(shortest_path(&graph, 3, 0), 7);
145 //! assert_eq!(shortest_path(&graph, 0, 4), 5);
146 //! assert_eq!(shortest_path(&graph, 4, 0), usize::MAX);
150 #![allow(missing_docs)]
151 #![stable(feature = "rust1", since = "1.0.0")]
153 use core
::prelude
::*;
155 use core
::iter
::{FromIterator}
;
156 use core
::mem
::{zeroed, replace, swap}
;
160 use vec
::{self, Vec}
;
162 /// A priority queue implemented with a binary heap.
164 /// This will be a max-heap.
166 /// It is a logic error for an item to be modified in such a way that the
167 /// item's ordering relative to any other item, as determined by the `Ord`
168 /// trait, changes while it is in the heap. This is normally only possible
169 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
171 #[stable(feature = "rust1", since = "1.0.0")]
172 pub struct BinaryHeap
<T
> {
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<T
: Ord
> Default
for BinaryHeap
<T
> {
179 fn default() -> BinaryHeap
<T
> { BinaryHeap::new() }
182 impl<T
: Ord
> BinaryHeap
<T
> {
183 /// Creates an empty `BinaryHeap` as a max-heap.
188 /// use std::collections::BinaryHeap;
189 /// let mut heap = BinaryHeap::new();
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub fn new() -> BinaryHeap
<T
> { BinaryHeap { data: vec![] }
}
195 /// Creates an empty `BinaryHeap` with a specific capacity.
196 /// This preallocates enough memory for `capacity` elements,
197 /// so that the `BinaryHeap` does not have to be reallocated
198 /// until it contains at least that many values.
203 /// use std::collections::BinaryHeap;
204 /// let mut heap = BinaryHeap::with_capacity(10);
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn with_capacity(capacity
: usize) -> BinaryHeap
<T
> {
209 BinaryHeap { data: Vec::with_capacity(capacity) }
212 /// Creates a `BinaryHeap` from a vector. This is sometimes called
213 /// `heapifying` the vector.
218 /// # #![feature(collections)]
219 /// use std::collections::BinaryHeap;
220 /// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
222 pub fn from_vec(vec
: Vec
<T
>) -> BinaryHeap
<T
> {
223 let mut heap
= BinaryHeap { data: vec }
;
224 let mut n
= heap
.len() / 2;
232 /// Returns an iterator visiting all values in the underlying vector, in
238 /// # #![feature(collections)]
239 /// use std::collections::BinaryHeap;
240 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
242 /// // Print 1, 2, 3, 4 in arbitrary order
243 /// for x in heap.iter() {
244 /// println!("{}", x);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn iter(&self) -> Iter
<T
> {
249 Iter { iter: self.data.iter() }
252 /// Returns the greatest item in the binary heap, or `None` if it is empty.
257 /// use std::collections::BinaryHeap;
258 /// let mut heap = BinaryHeap::new();
259 /// assert_eq!(heap.peek(), None);
264 /// assert_eq!(heap.peek(), Some(&5));
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn peek(&self) -> Option
<&T
> {
272 /// Returns the number of elements the binary heap can hold without reallocating.
277 /// use std::collections::BinaryHeap;
278 /// let mut heap = BinaryHeap::with_capacity(100);
279 /// assert!(heap.capacity() >= 100);
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn capacity(&self) -> usize { self.data.capacity() }
285 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
286 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
288 /// Note that the allocator may give the collection more space than it requests. Therefore
289 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
290 /// insertions are expected.
294 /// Panics if the new capacity overflows `usize`.
299 /// use std::collections::BinaryHeap;
300 /// let mut heap = BinaryHeap::new();
301 /// heap.reserve_exact(100);
302 /// assert!(heap.capacity() >= 100);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn reserve_exact(&mut self, additional
: usize) {
307 self.data
.reserve_exact(additional
);
310 /// Reserves capacity for at least `additional` more elements to be inserted in the
311 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
315 /// Panics if the new capacity overflows `usize`.
320 /// use std::collections::BinaryHeap;
321 /// let mut heap = BinaryHeap::new();
322 /// heap.reserve(100);
323 /// assert!(heap.capacity() >= 100);
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn reserve(&mut self, additional
: usize) {
328 self.data
.reserve(additional
);
331 /// Discards as much additional capacity as possible.
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn shrink_to_fit(&mut self) {
334 self.data
.shrink_to_fit();
337 /// Removes the greatest item from the binary heap and returns it, or `None` if it
343 /// # #![feature(collections)]
344 /// use std::collections::BinaryHeap;
345 /// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
347 /// assert_eq!(heap.pop(), Some(3));
348 /// assert_eq!(heap.pop(), Some(1));
349 /// assert_eq!(heap.pop(), None);
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn pop(&mut self) -> Option
<T
> {
353 self.data
.pop().map(|mut item
| {
354 if !self.is_empty() {
355 swap(&mut item
, &mut self.data
[0]);
362 /// Pushes an item onto the binary heap.
367 /// use std::collections::BinaryHeap;
368 /// let mut heap = BinaryHeap::new();
373 /// assert_eq!(heap.len(), 3);
374 /// assert_eq!(heap.peek(), Some(&5));
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn push(&mut self, item
: T
) {
378 let old_len
= self.len();
379 self.data
.push(item
);
380 self.sift_up(0, old_len
);
383 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
384 /// an optimized fashion.
389 /// # #![feature(collections)]
390 /// use std::collections::BinaryHeap;
391 /// let mut heap = BinaryHeap::new();
395 /// assert_eq!(heap.push_pop(3), 5);
396 /// assert_eq!(heap.push_pop(9), 9);
397 /// assert_eq!(heap.len(), 2);
398 /// assert_eq!(heap.peek(), Some(&3));
400 pub fn push_pop(&mut self, mut item
: T
) -> T
{
401 match self.data
.get_mut(0) {
403 Some(top
) => if *top
> item
{
404 swap(&mut item
, top
);
414 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
415 /// an optimized fashion. The push is done regardless of whether the binary heap
421 /// # #![feature(collections)]
422 /// use std::collections::BinaryHeap;
423 /// let mut heap = BinaryHeap::new();
425 /// assert_eq!(heap.replace(1), None);
426 /// assert_eq!(heap.replace(3), Some(1));
427 /// assert_eq!(heap.len(), 1);
428 /// assert_eq!(heap.peek(), Some(&3));
430 pub fn replace(&mut self, mut item
: T
) -> Option
<T
> {
431 if !self.is_empty() {
432 swap(&mut item
, &mut self.data
[0]);
441 /// Consumes the `BinaryHeap` and returns the underlying vector
442 /// in arbitrary order.
447 /// # #![feature(collections)]
448 /// use std::collections::BinaryHeap;
449 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
450 /// let vec = heap.into_vec();
452 /// // Will print in some order
453 /// for x in vec.iter() {
454 /// println!("{}", x);
457 pub fn into_vec(self) -> Vec
<T
> { self.data }
459 /// Consumes the `BinaryHeap` and returns a vector in sorted
460 /// (ascending) order.
465 /// # #![feature(collections)]
466 /// use std::collections::BinaryHeap;
468 /// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
472 /// let vec = heap.into_sorted_vec();
473 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
475 pub fn into_sorted_vec(mut self) -> Vec
<T
> {
476 let mut end
= self.len();
479 self.data
.swap(0, end
);
480 self.sift_down_range(0, end
);
485 // The implementations of sift_up and sift_down use unsafe blocks in
486 // order to move an element out of the vector (leaving behind a
487 // zeroed element), shift along the others and move it back into the
488 // vector over the junk element. This reduces the constant factor
489 // compared to using swaps, which involves twice as many moves.
490 fn sift_up(&mut self, start
: usize, mut pos
: usize) {
492 let new
= replace(&mut self.data
[pos
], zeroed());
495 let parent
= (pos
- 1) >> 1;
497 if new
<= self.data
[parent
] { break; }
499 let x
= replace(&mut self.data
[parent
], zeroed());
500 ptr
::write(&mut self.data
[pos
], x
);
503 ptr
::write(&mut self.data
[pos
], new
);
507 fn sift_down_range(&mut self, mut pos
: usize, end
: usize) {
510 let new
= replace(&mut self.data
[pos
], zeroed());
512 let mut child
= 2 * pos
+ 1;
514 let right
= child
+ 1;
515 if right
< end
&& !(self.data
[child
] > self.data
[right
]) {
518 let x
= replace(&mut self.data
[child
], zeroed());
519 ptr
::write(&mut self.data
[pos
], x
);
524 ptr
::write(&mut self.data
[pos
], new
);
525 self.sift_up(start
, pos
);
529 fn sift_down(&mut self, pos
: usize) {
530 let len
= self.len();
531 self.sift_down_range(pos
, len
);
534 /// Returns the length of the binary heap.
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn len(&self) -> usize { self.data.len() }
538 /// Checks if the binary heap is empty.
539 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn is_empty(&self) -> bool { self.len() == 0 }
542 /// Clears the binary heap, returning an iterator over the removed elements.
544 /// The elements are removed in arbitrary order.
546 #[unstable(feature = "collections",
547 reason
= "matches collection reform specification, waiting for dust to settle")]
548 pub fn drain(&mut self) -> Drain
<T
> {
549 Drain { iter: self.data.drain() }
552 /// Drops all items from the binary heap.
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn clear(&mut self) { self.drain(); }
557 /// `BinaryHeap` iterator.
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub struct Iter
<'a
, T
: 'a
> {
560 iter
: slice
::Iter
<'a
, T
>,
563 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<'a
, T
> Clone
for Iter
<'a
, T
> {
566 fn clone(&self) -> Iter
<'a
, T
> {
567 Iter { iter: self.iter.clone() }
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
576 fn next(&mut self) -> Option
<&'a T
> { self.iter.next() }
579 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
585 fn next_back(&mut self) -> Option
<&'a T
> { self.iter.next_back() }
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl<'a
, T
> ExactSizeIterator
for Iter
<'a
, T
> {}
591 /// An iterator that moves out of a `BinaryHeap`.
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub struct IntoIter
<T
> {
594 iter
: vec
::IntoIter
<T
>,
597 #[stable(feature = "rust1", since = "1.0.0")]
598 impl<T
> Iterator
for IntoIter
<T
> {
602 fn next(&mut self) -> Option
<T
> { self.iter.next() }
605 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
611 fn next_back(&mut self) -> Option
<T
> { self.iter.next_back() }
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
617 /// An iterator that drains a `BinaryHeap`.
618 #[unstable(feature = "collections", reason = "recent addition")]
619 pub struct Drain
<'a
, T
: 'a
> {
620 iter
: vec
::Drain
<'a
, T
>,
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl<'a
, T
: 'a
> Iterator
for Drain
<'a
, T
> {
628 fn next(&mut self) -> Option
<T
> { self.iter.next() }
631 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
634 #[stable(feature = "rust1", since = "1.0.0")]
635 impl<'a
, T
: 'a
> DoubleEndedIterator
for Drain
<'a
, T
> {
637 fn next_back(&mut self) -> Option
<T
> { self.iter.next_back() }
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<'a
, T
: 'a
> ExactSizeIterator
for Drain
<'a
, T
> {}
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T
: Ord
> FromIterator
<T
> for BinaryHeap
<T
> {
645 fn from_iter
<I
: IntoIterator
<Item
=T
>>(iter
: I
) -> BinaryHeap
<T
> {
646 BinaryHeap
::from_vec(iter
.into_iter().collect())
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T
: Ord
> IntoIterator
for BinaryHeap
<T
> {
653 type IntoIter
= IntoIter
<T
>;
655 /// Creates a consuming iterator, that is, one that moves each value out of
656 /// the binary heap in arbitrary order. The binary heap cannot be used
657 /// after calling this.
662 /// # #![feature(collections)]
663 /// use std::collections::BinaryHeap;
664 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
666 /// // Print 1, 2, 3, 4 in arbitrary order
667 /// for x in heap.into_iter() {
668 /// // x has type i32, not &i32
669 /// println!("{}", x);
672 fn into_iter(self) -> IntoIter
<T
> {
673 IntoIter { iter: self.data.into_iter() }
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<'a
, T
> IntoIterator
for &'a BinaryHeap
<T
> where T
: Ord
{
680 type IntoIter
= Iter
<'a
, T
>;
682 fn into_iter(self) -> Iter
<'a
, T
> {
687 #[stable(feature = "rust1", since = "1.0.0")]
688 impl<T
: Ord
> Extend
<T
> for BinaryHeap
<T
> {
689 fn extend
<I
: IntoIterator
<Item
=T
>>(&mut self, iterable
: I
) {
690 let iter
= iterable
.into_iter();
691 let (lower
, _
) = iter
.size_hint();