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, 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 `uint`, 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 `uint::MAX` as a sentinel value,
67 //! // for a simpler implementation.
68 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
69 //! // dist[node] = current shortest distance from `start` to `node`
70 //! let mut dist: Vec<_> = range(0, adj_list.len()).map(|_| uint::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), uint::MAX);
150 #![allow(missing_docs)]
152 use core::prelude::*;
154 use core::default::Default;
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.
167 pub struct BinaryHeap<T> {
172 impl<T: Ord> Default for BinaryHeap<T> {
174 fn default() -> BinaryHeap<T> { BinaryHeap::new() }
177 impl<T: Ord> BinaryHeap<T> {
178 /// Creates an empty `BinaryHeap` as a max-heap.
183 /// use std::collections::BinaryHeap;
184 /// let mut heap = BinaryHeap::new();
188 pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
190 /// Creates an empty `BinaryHeap` with a specific capacity.
191 /// This preallocates enough memory for `capacity` elements,
192 /// so that the `BinaryHeap` does not have to be reallocated
193 /// until it contains at least that many values.
198 /// use std::collections::BinaryHeap;
199 /// let mut heap = BinaryHeap::with_capacity(10);
203 pub fn with_capacity(capacity: uint) -> BinaryHeap<T> {
204 BinaryHeap { data: Vec::with_capacity(capacity) }
207 /// Creates a `BinaryHeap` from a vector. This is sometimes called
208 /// `heapifying` the vector.
213 /// use std::collections::BinaryHeap;
214 /// let heap = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]);
216 pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
217 let mut heap = BinaryHeap { data: vec };
218 let mut n = heap.len() / 2;
226 /// Returns an iterator visiting all values in the underlying vector, in
232 /// use std::collections::BinaryHeap;
233 /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
235 /// // Print 1, 2, 3, 4 in arbitrary order
236 /// for x in heap.iter() {
237 /// println!("{}", x);
241 pub fn iter(&self) -> Iter<T> {
242 Iter { iter: self.data.iter() }
245 /// Creates a consuming iterator, that is, one that moves each value out of
246 /// the binary heap in arbitrary order. The binary heap cannot be used
247 /// after calling this.
252 /// use std::collections::BinaryHeap;
253 /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
255 /// // Print 1, 2, 3, 4 in arbitrary order
256 /// for x in heap.into_iter() {
257 /// // x has type int, not &int
258 /// println!("{}", x);
262 pub fn into_iter(self) -> IntoIter<T> {
263 IntoIter { iter: self.data.into_iter() }
266 /// Returns the greatest item in the binary heap, or `None` if it is empty.
271 /// use std::collections::BinaryHeap;
272 /// let mut heap = BinaryHeap::new();
273 /// assert_eq!(heap.peek(), None);
278 /// assert_eq!(heap.peek(), Some(&5));
282 pub fn peek(&self) -> Option<&T> {
286 /// Returns the number of elements the binary heap can hold without reallocating.
291 /// use std::collections::BinaryHeap;
292 /// let mut heap = BinaryHeap::with_capacity(100);
293 /// assert!(heap.capacity() >= 100);
297 pub fn capacity(&self) -> uint { self.data.capacity() }
299 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
300 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
302 /// Note that the allocator may give the collection more space than it requests. Therefore
303 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
304 /// insertions are expected.
308 /// Panics if the new capacity overflows `uint`.
313 /// use std::collections::BinaryHeap;
314 /// let mut heap = BinaryHeap::new();
315 /// heap.reserve_exact(100);
316 /// assert!(heap.capacity() >= 100);
320 pub fn reserve_exact(&mut self, additional: uint) {
321 self.data.reserve_exact(additional);
324 /// Reserves capacity for at least `additional` more elements to be inserted in the
325 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
329 /// Panics if the new capacity overflows `uint`.
334 /// use std::collections::BinaryHeap;
335 /// let mut heap = BinaryHeap::new();
336 /// heap.reserve(100);
337 /// assert!(heap.capacity() >= 100);
341 pub fn reserve(&mut self, additional: uint) {
342 self.data.reserve(additional);
345 /// Discards as much additional capacity as possible.
347 pub fn shrink_to_fit(&mut self) {
348 self.data.shrink_to_fit();
351 /// Removes the greatest item from the binary heap and returns it, or `None` if it
357 /// use std::collections::BinaryHeap;
358 /// let mut heap = BinaryHeap::from_vec(vec![1i, 3]);
360 /// assert_eq!(heap.pop(), Some(3));
361 /// assert_eq!(heap.pop(), Some(1));
362 /// assert_eq!(heap.pop(), None);
365 pub fn pop(&mut self) -> Option<T> {
366 self.data.pop().map(|mut item| {
367 if !self.is_empty() {
368 swap(&mut item, &mut self.data[0]);
375 /// Pushes an item onto the binary heap.
380 /// use std::collections::BinaryHeap;
381 /// let mut heap = BinaryHeap::new();
386 /// assert_eq!(heap.len(), 3);
387 /// assert_eq!(heap.peek(), Some(&5));
390 pub fn push(&mut self, item: T) {
391 let old_len = self.len();
392 self.data.push(item);
393 self.sift_up(0, old_len);
396 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
397 /// an optimized fashion.
402 /// use std::collections::BinaryHeap;
403 /// let mut heap = BinaryHeap::new();
407 /// assert_eq!(heap.push_pop(3), 5);
408 /// assert_eq!(heap.push_pop(9), 9);
409 /// assert_eq!(heap.len(), 2);
410 /// assert_eq!(heap.peek(), Some(&3));
412 pub fn push_pop(&mut self, mut item: T) -> T {
413 match self.data.get_mut(0) {
415 Some(top) => if *top > item {
416 swap(&mut item, top);
426 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
427 /// an optimized fashion. The push is done regardless of whether the binary heap
433 /// use std::collections::BinaryHeap;
434 /// let mut heap = BinaryHeap::new();
436 /// assert_eq!(heap.replace(1i), None);
437 /// assert_eq!(heap.replace(3), Some(1));
438 /// assert_eq!(heap.len(), 1);
439 /// assert_eq!(heap.peek(), Some(&3));
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;
459 /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
460 /// let vec = heap.into_vec();
462 /// // Will print in some order
463 /// for x in vec.iter() {
464 /// println!("{}", x);
467 pub fn into_vec(self) -> Vec<T> { self.data }
469 /// Consumes the `BinaryHeap` and returns a vector in sorted
470 /// (ascending) order.
475 /// use std::collections::BinaryHeap;
477 /// let mut heap = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]);
481 /// let vec = heap.into_sorted_vec();
482 /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
484 pub fn into_sorted_vec(mut self) -> Vec<T> {
485 let mut end = self.len();
488 self.data.swap(0, end);
489 self.sift_down_range(0, end);
494 // The implementations of sift_up and sift_down use unsafe blocks in
495 // order to move an element out of the vector (leaving behind a
496 // zeroed element), shift along the others and move it back into the
497 // vector over the junk element. This reduces the constant factor
498 // compared to using swaps, which involves twice as many moves.
499 fn sift_up(&mut self, start: uint, mut pos: uint) {
501 let new = replace(&mut self.data[pos], zeroed());
504 let parent = (pos - 1) >> 1;
506 if new <= self.data[parent] { break; }
508 let x = replace(&mut self.data[parent], zeroed());
509 ptr::write(&mut self.data[pos], x);
512 ptr::write(&mut self.data[pos], new);
516 fn sift_down_range(&mut self, mut pos: uint, end: uint) {
519 let new = replace(&mut self.data[pos], zeroed());
521 let mut child = 2 * pos + 1;
523 let right = child + 1;
524 if right < end && !(self.data[child] > self.data[right]) {
527 let x = replace(&mut self.data[child], zeroed());
528 ptr::write(&mut self.data[pos], x);
533 ptr::write(&mut self.data[pos], new);
534 self.sift_up(start, pos);
538 fn sift_down(&mut self, pos: uint) {
539 let len = self.len();
540 self.sift_down_range(pos, len);
543 /// Returns the length of the binary heap.
545 pub fn len(&self) -> uint { self.data.len() }
547 /// Checks if the binary heap is empty.
549 pub fn is_empty(&self) -> bool { self.len() == 0 }
551 /// Clears the binary heap, returning an iterator over the removed elements.
553 #[unstable = "matches collection reform specification, waiting for dust to settle"]
554 pub fn drain(&mut self) -> Drain<T> {
555 Drain { iter: self.data.drain() }
558 /// Drops all items from the binary heap.
560 pub fn clear(&mut self) { self.drain(); }
563 /// `BinaryHeap` iterator.
564 pub struct Iter <'a, T: 'a> {
565 iter: slice::Iter<'a, T>,
568 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
569 impl<'a, T> Clone for Iter<'a, T> {
570 fn clone(&self) -> Iter<'a, T> {
571 Iter { iter: self.iter.clone() }
576 impl<'a, T> Iterator for Iter<'a, T> {
580 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
583 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
587 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
589 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
593 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
595 /// An iterator that moves out of a `BinaryHeap`.
596 pub struct IntoIter<T> {
597 iter: vec::IntoIter<T>,
601 impl<T> Iterator for IntoIter<T> {
605 fn next(&mut self) -> Option<T> { self.iter.next() }
608 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
612 impl<T> DoubleEndedIterator for IntoIter<T> {
614 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
618 impl<T> ExactSizeIterator for IntoIter<T> {}
620 /// An iterator that drains a `BinaryHeap`.
621 pub struct Drain<'a, T: 'a> {
622 iter: vec::Drain<'a, T>,
626 impl<'a, T: 'a> Iterator for Drain<'a, T> {
630 fn next(&mut self) -> Option<T> { self.iter.next() }
633 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
637 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
639 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
643 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
646 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
647 fn from_iter<Iter: Iterator<Item=T>>(iter: Iter) -> BinaryHeap<T> {
648 BinaryHeap::from_vec(iter.collect())
653 impl<T: Ord> Extend<T> for BinaryHeap<T> {
654 fn extend<Iter: Iterator<Item=T>>(&mut self, mut iter: Iter) {
655 let (lower, _) = iter.size_hint();
669 use super::BinaryHeap;
673 let data = vec!(5i, 9, 3);
674 let iterout = [9i, 5, 3];
675 let heap = BinaryHeap::from_vec(data);
677 for el in heap.iter() {
678 assert_eq!(*el, iterout[i]);
684 fn test_iterator_reverse() {
685 let data = vec!(5i, 9, 3);
686 let iterout = vec!(3i, 5, 9);
687 let pq = BinaryHeap::from_vec(data);
689 let v: Vec<int> = pq.iter().rev().map(|&x| x).collect();
690 assert_eq!(v, iterout);
694 fn test_move_iter() {
695 let data = vec!(5i, 9, 3);
696 let iterout = vec!(9i, 5, 3);
697 let pq = BinaryHeap::from_vec(data);
699 let v: Vec<int> = pq.into_iter().collect();
700 assert_eq!(v, iterout);
704 fn test_move_iter_size_hint() {
705 let data = vec!(5i, 9);
706 let pq = BinaryHeap::from_vec(data);
708 let mut it = pq.into_iter();
710 assert_eq!(it.size_hint(), (2, Some(2)));
711 assert_eq!(it.next(), Some(9i));
713 assert_eq!(it.size_hint(), (1, Some(1)));
714 assert_eq!(it.next(), Some(5i));
716 assert_eq!(it.size_hint(), (0, Some(0)));
717 assert_eq!(it.next(), None);
721 fn test_move_iter_reverse() {
722 let data = vec!(5i, 9, 3);
723 let iterout = vec!(3i, 5, 9);
724 let pq = BinaryHeap::from_vec(data);
726 let v: Vec<int> = pq.into_iter().rev().collect();
727 assert_eq!(v, iterout);
731 fn test_peek_and_pop() {
732 let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
733 let mut sorted = data.clone();
735 let mut heap = BinaryHeap::from_vec(data);
736 while !heap.is_empty() {
737 assert_eq!(heap.peek().unwrap(), sorted.last().unwrap());
738 assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
744 let mut heap = BinaryHeap::from_vec(vec!(2i, 4, 9));
745 assert_eq!(heap.len(), 3);
746 assert!(*heap.peek().unwrap() == 9);
748 assert_eq!(heap.len(), 4);
749 assert!(*heap.peek().unwrap() == 11);
751 assert_eq!(heap.len(), 5);
752 assert!(*heap.peek().unwrap() == 11);
754 assert_eq!(heap.len(), 6);
755 assert!(*heap.peek().unwrap() == 27);
757 assert_eq!(heap.len(), 7);
758 assert!(*heap.peek().unwrap() == 27);
760 assert_eq!(heap.len(), 8);
761 assert!(*heap.peek().unwrap() == 103);
765 fn test_push_unique() {
766 let mut heap = BinaryHeap::from_vec(vec!(box 2i, box 4, box 9));
767 assert_eq!(heap.len(), 3);
768 assert!(*heap.peek().unwrap() == box 9);
770 assert_eq!(heap.len(), 4);
771 assert!(*heap.peek().unwrap() == box 11);
773 assert_eq!(heap.len(), 5);
774 assert!(*heap.peek().unwrap() == box 11);
776 assert_eq!(heap.len(), 6);
777 assert!(*heap.peek().unwrap() == box 27);
779 assert_eq!(heap.len(), 7);
780 assert!(*heap.peek().unwrap() == box 27);
782 assert_eq!(heap.len(), 8);
783 assert!(*heap.peek().unwrap() == box 103);
788 let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
789 assert_eq!(heap.len(), 5);
790 assert_eq!(heap.push_pop(6), 6);
791 assert_eq!(heap.len(), 5);
792 assert_eq!(heap.push_pop(0), 5);
793 assert_eq!(heap.len(), 5);
794 assert_eq!(heap.push_pop(4), 5);
795 assert_eq!(heap.len(), 5);
796 assert_eq!(heap.push_pop(1), 4);
797 assert_eq!(heap.len(), 5);
802 let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
803 assert_eq!(heap.len(), 5);
804 assert_eq!(heap.replace(6).unwrap(), 5);
805 assert_eq!(heap.len(), 5);
806 assert_eq!(heap.replace(0).unwrap(), 6);
807 assert_eq!(heap.len(), 5);
808 assert_eq!(heap.replace(4).unwrap(), 5);
809 assert_eq!(heap.len(), 5);
810 assert_eq!(heap.replace(1).unwrap(), 4);
811 assert_eq!(heap.len(), 5);
814 fn check_to_vec(mut data: Vec<int>) {
815 let heap = BinaryHeap::from_vec(data.clone());
816 let mut v = heap.clone().into_vec();
821 assert_eq!(heap.into_sorted_vec(), data);
826 check_to_vec(vec!());
827 check_to_vec(vec!(5i));
828 check_to_vec(vec!(3i, 2));
829 check_to_vec(vec!(2i, 3));
830 check_to_vec(vec!(5i, 1, 2));
831 check_to_vec(vec!(1i, 100, 2, 3));
832 check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
833 check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
834 check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
835 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
836 check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
837 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
838 check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
842 fn test_empty_pop() {
843 let mut heap = BinaryHeap::<int>::new();
844 assert!(heap.pop().is_none());
848 fn test_empty_peek() {
849 let empty = BinaryHeap::<int>::new();
850 assert!(empty.peek().is_none());
854 fn test_empty_replace() {
855 let mut heap = BinaryHeap::<int>::new();
856 assert!(heap.replace(5).is_none());
860 fn test_from_iter() {
861 let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
863 let mut q: BinaryHeap<uint> = xs.iter().rev().map(|&x| x).collect();
865 for &x in xs.iter() {
866 assert_eq!(q.pop().unwrap(), x);
872 let mut q: BinaryHeap<_> =
873 [9u, 8, 7, 6, 5, 4, 3, 2, 1].iter().cloned().collect();
875 assert_eq!(q.drain().take(5).count(), 5);
877 assert!(q.is_empty());