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 priority queue can be done in-place, and has `O(n)`
15 //! complexity. A priority queue 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 which implements [Dijkstra's algorithm][dijkstra]
21 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
22 //! It showcases how to use the `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::collections::BinaryHeap;
32 //! #[deriving(Eq, PartialEq)]
38 //! impl Copy for State {}
40 //! // The priority queue depends on `Ord`.
41 //! // Explicitly implement the trait so the queue becomes a min-heap
42 //! // instead of a max-heap.
43 //! impl Ord for State {
44 //! fn cmp(&self, other: &State) -> Ordering {
45 //! // Notice that the we flip the ordering here
46 //! other.cost.cmp(&self.cost)
50 //! // `PartialOrd` needs to be implemented as well.
51 //! impl PartialOrd for State {
52 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
53 //! Some(self.cmp(other))
57 //! // Each node is represented as an `uint`, for a shorter implementation.
63 //! // Dijkstra's shortest path algorithm.
65 //! // Start at `start` and use `dist` to track the current shortest distance
66 //! // to each node. This implementation isn't memory efficient as it may leave duplicate
67 //! // nodes in the queue. It also uses `uint::MAX` as a sentinel value,
68 //! // for a simpler implementation.
69 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
70 //! // dist[node] = current shortest distance from `start` to `node`
71 //! let mut dist = Vec::from_elem(adj_list.len(), uint::MAX);
73 //! let mut heap = BinaryHeap::new();
75 //! // We're at `start`, with a zero cost
77 //! heap.push(State { cost: 0u, position: start });
79 //! // Examine the frontier with lower cost nodes first (min-heap)
81 //! let State { cost, position } = match heap.pop() {
82 //! None => break, // empty
86 //! // Alternatively we could have continued to find all shortest paths
87 //! if position == goal { return cost }
89 //! // Important as we may have already found a better way
90 //! if cost > dist[position] { continue }
92 //! // For each node we can reach, see if we can find a way with
93 //! // a lower cost going through this node
94 //! for edge in adj_list[position].iter() {
95 //! let next = State { cost: cost + edge.cost, position: edge.node };
97 //! // If so, add it to the frontier and continue
98 //! if next.cost < dist[next.position] {
100 //! // Relaxation, we have now found a better way
101 //! dist[next.position] = next.cost;
106 //! // Goal not reachable
111 //! // This is the directed graph we're going to use.
112 //! // The node numbers correspond to the different states,
113 //! // and the edge weights symbolises the cost of moving
114 //! // from one node to another.
115 //! // Note that the edges are one-way.
118 //! // +-----------------+
121 //! // 0 -----> 1 -----> 3 ---> 4
125 //! // +------> 2 -------+ |
127 //! // +---------------+
129 //! // The graph is represented as an adjacency list where each index,
130 //! // corresponding to a node value, has a list of outgoing edges.
131 //! // Chosen for it's efficiency.
132 //! let graph = vec![
134 //! vec![Edge { node: 2, cost: 10 },
135 //! Edge { node: 1, cost: 1 }],
137 //! vec![Edge { node: 3, cost: 2 }],
139 //! vec![Edge { node: 1, cost: 1 },
140 //! Edge { node: 3, cost: 3 },
141 //! Edge { node: 4, cost: 1 }],
143 //! vec![Edge { node: 0, cost: 7 },
144 //! Edge { node: 4, cost: 2 }],
148 //! assert_eq!(shortest_path(&graph, 0, 1), 1);
149 //! assert_eq!(shortest_path(&graph, 0, 3), 3);
150 //! assert_eq!(shortest_path(&graph, 3, 0), 7);
151 //! assert_eq!(shortest_path(&graph, 0, 4), 5);
152 //! assert_eq!(shortest_path(&graph, 4, 0), uint::MAX);
156 #![allow(missing_docs)]
158 use core::prelude::*;
160 use core::default::Default;
161 use core::mem::{zeroed, replace, swap};
167 /// A priority queue implemented with a binary heap.
169 /// This will be a max-heap.
171 pub struct BinaryHeap<T> {
175 impl<T: Ord> Default for BinaryHeap<T> {
177 fn default() -> BinaryHeap<T> { BinaryHeap::new() }
180 impl<T: Ord> BinaryHeap<T> {
181 /// Creates an empty `BinaryHeap` as a max-heap.
186 /// use std::collections::BinaryHeap;
187 /// let heap: BinaryHeap<uint> = BinaryHeap::new();
189 #[unstable = "matches collection reform specification, waiting for dust to settle"]
190 pub fn new() -> BinaryHeap<T> { BinaryHeap{data: vec!(),} }
192 /// Creates an empty `BinaryHeap` with a specific capacity.
193 /// This preallocates enough memory for `capacity` elements,
194 /// so that the `BinaryHeap` does not have to be reallocated
195 /// until it contains at least that many values.
200 /// use std::collections::BinaryHeap;
201 /// let heap: BinaryHeap<uint> = BinaryHeap::with_capacity(10u);
203 #[unstable = "matches collection reform specification, waiting for dust to settle"]
204 pub fn with_capacity(capacity: uint) -> BinaryHeap<T> {
205 BinaryHeap { data: Vec::with_capacity(capacity) }
208 /// Creates a `BinaryHeap` from a vector. This is sometimes called
209 /// `heapifying` the vector.
214 /// use std::collections::BinaryHeap;
215 /// let heap = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]);
217 pub fn from_vec(xs: Vec<T>) -> BinaryHeap<T> {
218 let mut q = BinaryHeap{data: xs,};
219 let mut n = q.len() / 2;
227 /// An iterator visiting all values in underlying vector, in
233 /// use std::collections::BinaryHeap;
234 /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
236 /// // Print 1, 2, 3, 4 in arbitrary order
237 /// for x in heap.iter() {
238 /// println!("{}", x);
241 #[unstable = "matches collection reform specification, waiting for dust to settle"]
242 pub fn iter<'a>(&'a self) -> Items<'a, T> {
243 Items { iter: self.data.iter() }
246 /// Creates a consuming iterator, that is, one that moves each value out of
247 /// the binary heap in arbitrary order. The binary heap cannot be used
248 /// after calling this.
253 /// use std::collections::BinaryHeap;
254 /// let pq = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
256 /// // Print 1, 2, 3, 4 in arbitrary order
257 /// for x in pq.into_iter() {
258 /// // x has type int, not &int
259 /// println!("{}", x);
262 #[unstable = "matches collection reform specification, waiting for dust to settle"]
263 pub fn into_iter(self) -> MoveItems<T> {
264 MoveItems { iter: self.data.into_iter() }
267 /// Returns the greatest item in a queue, or `None` if it is empty.
272 /// use std::collections::BinaryHeap;
274 /// let mut heap = BinaryHeap::new();
275 /// assert_eq!(heap.top(), None);
280 /// assert_eq!(heap.top(), Some(&5i));
283 pub fn top<'a>(&'a self) -> Option<&'a T> {
284 if self.is_empty() { None } else { Some(&self.data[0]) }
287 /// Returns the number of elements the queue can hold without reallocating.
292 /// use std::collections::BinaryHeap;
294 /// let heap: BinaryHeap<uint> = BinaryHeap::with_capacity(100u);
295 /// assert!(heap.capacity() >= 100u);
297 #[unstable = "matches collection reform specification, waiting for dust to settle"]
298 pub fn capacity(&self) -> uint { self.data.capacity() }
300 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
301 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
303 /// Note that the allocator may give the collection more space than it requests. Therefore
304 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
305 /// insertions are expected.
309 /// Panics if the new capacity overflows `uint`.
314 /// use std::collections::BinaryHeap;
316 /// let mut heap: BinaryHeap<uint> = BinaryHeap::new();
317 /// heap.reserve_exact(100u);
318 /// assert!(heap.capacity() >= 100u);
320 #[unstable = "matches collection reform specification, waiting for dust to settle"]
321 pub fn reserve_exact(&mut self, additional: uint) { self.data.reserve_exact(additional) }
323 /// Reserves capacity for at least `additional` more elements to be inserted in the
324 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
328 /// Panics if the new capacity overflows `uint`.
333 /// use std::collections::BinaryHeap;
335 /// let mut heap: BinaryHeap<uint> = BinaryHeap::new();
336 /// heap.reserve(100u);
337 /// assert!(heap.capacity() >= 100u);
339 #[unstable = "matches collection reform specification, waiting for dust to settle"]
340 pub fn reserve(&mut self, additional: uint) {
341 self.data.reserve(additional)
344 /// Discards as much additional capacity as possible.
345 #[unstable = "matches collection reform specification, waiting for dust to settle"]
346 pub fn shrink_to_fit(&mut self) {
347 self.data.shrink_to_fit()
350 /// Removes the greatest item from a queue and returns it, or `None` if it
356 /// use std::collections::BinaryHeap;
358 /// let mut heap = BinaryHeap::from_vec(vec![1i, 3]);
360 /// assert_eq!(heap.pop(), Some(3i));
361 /// assert_eq!(heap.pop(), Some(1i));
362 /// assert_eq!(heap.pop(), None);
364 #[unstable = "matches collection reform specification, waiting for dust to settle"]
365 pub fn pop(&mut self) -> Option<T> {
366 match self.data.pop() {
369 if !self.is_empty() {
370 swap(&mut item, &mut self.data[0]);
378 /// Pushes an item onto the queue.
383 /// use std::collections::BinaryHeap;
385 /// let mut heap = BinaryHeap::new();
390 /// assert_eq!(heap.len(), 3);
391 /// assert_eq!(heap.top(), Some(&5i));
393 #[unstable = "matches collection reform specification, waiting for dust to settle"]
394 pub fn push(&mut self, item: T) {
395 self.data.push(item);
396 let new_len = self.len() - 1;
397 self.siftup(0, new_len);
400 /// Pushes an item onto a queue then pops the greatest item off the queue in
401 /// an optimized fashion.
406 /// use std::collections::BinaryHeap;
408 /// let mut heap = BinaryHeap::new();
412 /// assert_eq!(heap.push_pop(3i), 5);
413 /// assert_eq!(heap.push_pop(9i), 9);
414 /// assert_eq!(heap.len(), 2);
415 /// assert_eq!(heap.top(), Some(&3i));
417 pub fn push_pop(&mut self, mut item: T) -> T {
418 if !self.is_empty() && *self.top().unwrap() > item {
419 swap(&mut item, &mut self.data[0]);
425 /// Pops the greatest item off a queue then pushes an item onto the queue in
426 /// an optimized fashion. The push is done regardless of whether the queue
432 /// use std::collections::BinaryHeap;
434 /// let mut heap = BinaryHeap::new();
436 /// assert_eq!(heap.replace(1i), None);
437 /// assert_eq!(heap.replace(3i), Some(1i));
438 /// assert_eq!(heap.len(), 1);
439 /// assert_eq!(heap.top(), Some(&3i));
441 pub fn replace(&mut self, mut item: T) -> Option<T> {
442 if !self.is_empty() {
443 swap(&mut item, &mut self.data[0]);
452 /// Consumes the `BinaryHeap` and returns the underlying vector
453 /// in arbitrary order.
458 /// use std::collections::BinaryHeap;
460 /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
461 /// let vec = heap.into_vec();
463 /// // Will print in some order
464 /// for x in vec.iter() {
465 /// println!("{}", x);
468 pub fn into_vec(self) -> Vec<T> { let BinaryHeap{data: v} = self; v }
470 /// Consumes the `BinaryHeap` and returns a vector in sorted
471 /// (ascending) order.
476 /// use std::collections::BinaryHeap;
478 /// let mut heap = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]);
482 /// let vec = heap.into_sorted_vec();
483 /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
485 pub fn into_sorted_vec(self) -> Vec<T> {
487 let mut end = q.len();
491 q.siftdown_range(0, end)
496 // The implementations of siftup and siftdown use unsafe blocks in
497 // order to move an element out of the vector (leaving behind a
498 // zeroed element), shift along the others and move it back into the
499 // vector over the junk element. This reduces the constant factor
500 // compared to using swaps, which involves twice as many moves.
501 fn siftup(&mut self, start: uint, mut pos: uint) {
503 let new = replace(&mut self.data[pos], zeroed());
506 let parent = (pos - 1) >> 1;
507 if new > self.data[parent] {
508 let x = replace(&mut self.data[parent], zeroed());
509 ptr::write(&mut self.data[pos], x);
515 ptr::write(&mut self.data[pos], new);
519 fn siftdown_range(&mut self, mut pos: uint, end: uint) {
522 let new = replace(&mut self.data[pos], zeroed());
524 let mut child = 2 * pos + 1;
526 let right = child + 1;
527 if right < end && !(self.data[child] > self.data[right]) {
530 let x = replace(&mut self.data[child], zeroed());
531 ptr::write(&mut self.data[pos], x);
536 ptr::write(&mut self.data[pos], new);
537 self.siftup(start, pos);
541 fn siftdown(&mut self, pos: uint) {
542 let len = self.len();
543 self.siftdown_range(pos, len);
546 /// Returns the length of the queue.
547 #[unstable = "matches collection reform specification, waiting for dust to settle"]
548 pub fn len(&self) -> uint { self.data.len() }
550 /// Returns true if the queue contains no elements
551 #[unstable = "matches collection reform specification, waiting for dust to settle"]
552 pub fn is_empty(&self) -> bool { self.len() == 0 }
554 /// Drops all items from the queue.
555 #[unstable = "matches collection reform specification, waiting for dust to settle"]
556 pub fn clear(&mut self) { self.data.truncate(0) }
559 /// `BinaryHeap` iterator.
560 pub struct Items <'a, T:'a> {
561 iter: slice::Items<'a, T>,
564 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
566 fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
569 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
572 impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
574 fn next_back(&mut self) -> Option<(&'a T)> { self.iter.next_back() }
577 impl<'a, T> ExactSizeIterator<&'a T> for Items<'a, T> {}
579 /// An iterator that moves out of a `BinaryHeap`.
580 pub struct MoveItems<T> {
581 iter: vec::MoveItems<T>,
584 impl<T> Iterator<T> for MoveItems<T> {
586 fn next(&mut self) -> Option<T> { self.iter.next() }
589 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
592 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
594 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
597 impl<T> ExactSizeIterator<T> for MoveItems<T> {}
599 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
600 fn from_iter<Iter: Iterator<T>>(iter: Iter) -> BinaryHeap<T> {
601 let vec: Vec<T> = iter.collect();
602 BinaryHeap::from_vec(vec)
606 impl<T: Ord> Extend<T> for BinaryHeap<T> {
607 fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
608 let (lower, _) = iter.size_hint();
622 use super::BinaryHeap;
627 let data = vec!(5i, 9, 3);
628 let iterout = [9i, 5, 3];
629 let heap = BinaryHeap::from_vec(data);
631 for el in heap.iter() {
632 assert_eq!(*el, iterout[i]);
638 fn test_iterator_reverse() {
639 let data = vec!(5i, 9, 3);
640 let iterout = vec!(3i, 5, 9);
641 let pq = BinaryHeap::from_vec(data);
643 let v: Vec<int> = pq.iter().rev().map(|&x| x).collect();
644 assert_eq!(v, iterout);
648 fn test_move_iter() {
649 let data = vec!(5i, 9, 3);
650 let iterout = vec!(9i, 5, 3);
651 let pq = BinaryHeap::from_vec(data);
653 let v: Vec<int> = pq.into_iter().collect();
654 assert_eq!(v, iterout);
658 fn test_move_iter_size_hint() {
659 let data = vec!(5i, 9);
660 let pq = BinaryHeap::from_vec(data);
662 let mut it = pq.into_iter();
664 assert_eq!(it.size_hint(), (2, Some(2)));
665 assert_eq!(it.next(), Some(9i));
667 assert_eq!(it.size_hint(), (1, Some(1)));
668 assert_eq!(it.next(), Some(5i));
670 assert_eq!(it.size_hint(), (0, Some(0)));
671 assert_eq!(it.next(), None);
675 fn test_move_iter_reverse() {
676 let data = vec!(5i, 9, 3);
677 let iterout = vec!(3i, 5, 9);
678 let pq = BinaryHeap::from_vec(data);
680 let v: Vec<int> = pq.into_iter().rev().collect();
681 assert_eq!(v, iterout);
685 fn test_top_and_pop() {
686 let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
687 let mut sorted = data.clone();
689 let mut heap = BinaryHeap::from_vec(data);
690 while !heap.is_empty() {
691 assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
692 assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
698 let mut heap = BinaryHeap::from_vec(vec!(2i, 4, 9));
699 assert_eq!(heap.len(), 3);
700 assert!(*heap.top().unwrap() == 9);
702 assert_eq!(heap.len(), 4);
703 assert!(*heap.top().unwrap() == 11);
705 assert_eq!(heap.len(), 5);
706 assert!(*heap.top().unwrap() == 11);
708 assert_eq!(heap.len(), 6);
709 assert!(*heap.top().unwrap() == 27);
711 assert_eq!(heap.len(), 7);
712 assert!(*heap.top().unwrap() == 27);
714 assert_eq!(heap.len(), 8);
715 assert!(*heap.top().unwrap() == 103);
719 fn test_push_unique() {
720 let mut heap = BinaryHeap::from_vec(vec!(box 2i, box 4, box 9));
721 assert_eq!(heap.len(), 3);
722 assert!(*heap.top().unwrap() == box 9);
724 assert_eq!(heap.len(), 4);
725 assert!(*heap.top().unwrap() == box 11);
727 assert_eq!(heap.len(), 5);
728 assert!(*heap.top().unwrap() == box 11);
730 assert_eq!(heap.len(), 6);
731 assert!(*heap.top().unwrap() == box 27);
733 assert_eq!(heap.len(), 7);
734 assert!(*heap.top().unwrap() == box 27);
736 assert_eq!(heap.len(), 8);
737 assert!(*heap.top().unwrap() == box 103);
742 let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
743 assert_eq!(heap.len(), 5);
744 assert_eq!(heap.push_pop(6), 6);
745 assert_eq!(heap.len(), 5);
746 assert_eq!(heap.push_pop(0), 5);
747 assert_eq!(heap.len(), 5);
748 assert_eq!(heap.push_pop(4), 5);
749 assert_eq!(heap.len(), 5);
750 assert_eq!(heap.push_pop(1), 4);
751 assert_eq!(heap.len(), 5);
756 let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
757 assert_eq!(heap.len(), 5);
758 assert_eq!(heap.replace(6).unwrap(), 5);
759 assert_eq!(heap.len(), 5);
760 assert_eq!(heap.replace(0).unwrap(), 6);
761 assert_eq!(heap.len(), 5);
762 assert_eq!(heap.replace(4).unwrap(), 5);
763 assert_eq!(heap.len(), 5);
764 assert_eq!(heap.replace(1).unwrap(), 4);
765 assert_eq!(heap.len(), 5);
768 fn check_to_vec(mut data: Vec<int>) {
769 let heap = BinaryHeap::from_vec(data.clone());
770 let mut v = heap.clone().into_vec();
775 assert_eq!(heap.into_sorted_vec(), data);
780 check_to_vec(vec!());
781 check_to_vec(vec!(5i));
782 check_to_vec(vec!(3i, 2));
783 check_to_vec(vec!(2i, 3));
784 check_to_vec(vec!(5i, 1, 2));
785 check_to_vec(vec!(1i, 100, 2, 3));
786 check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
787 check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
788 check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
789 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
790 check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
791 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
792 check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
796 fn test_empty_pop() {
797 let mut heap: BinaryHeap<int> = BinaryHeap::new();
798 assert!(heap.pop().is_none());
802 fn test_empty_top() {
803 let empty: BinaryHeap<int> = BinaryHeap::new();
804 assert!(empty.top().is_none());
808 fn test_empty_replace() {
809 let mut heap: BinaryHeap<int> = BinaryHeap::new();
810 heap.replace(5).is_none();
814 fn test_from_iter() {
815 let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
817 let mut q: BinaryHeap<uint> = xs.iter().rev().map(|&x| x).collect();
819 for &x in xs.iter() {
820 assert_eq!(q.pop().unwrap(), x);