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 //! Insertions have `O(log n)` time complexity and checking or popping the largest element is
14 //! `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 `PriorityQueue` 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::PriorityQueue;
32 //! #[deriving(Eq, PartialEq)]
38 //! // The priority queue depends on `Ord`.
39 //! // Explicitly implement the trait so the queue becomes a min-heap
40 //! // instead of a max-heap.
41 //! impl Ord for State {
42 //! fn cmp(&self, other: &State) -> Ordering {
43 //! // Notice that the we flip the ordering here
44 //! other.cost.cmp(&self.cost)
48 //! // `PartialOrd` needs to be implemented as well.
49 //! impl PartialOrd for State {
50 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
51 //! Some(self.cmp(other))
55 //! // Each node is represented as an `uint`, for a shorter implementation.
61 //! // Dijkstra's shortest path algorithm.
63 //! // Start at `start` and use `dist` to track the current shortest distance
64 //! // to each node. This implementation isn't memory efficient as it may leave duplicate
65 //! // nodes in the queue. It also uses `uint::MAX` as a sentinel value,
66 //! // for a simpler implementation.
67 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
68 //! // dist[node] = current shortest distance from `start` to `node`
69 //! let mut dist = Vec::from_elem(adj_list.len(), uint::MAX);
71 //! let mut pq = PriorityQueue::new();
73 //! // We're at `start`, with a zero cost
74 //! *dist.get_mut(start) = 0u;
75 //! pq.push(State { cost: 0u, position: start });
77 //! // Examine the frontier with lower cost nodes first (min-heap)
79 //! let State { cost, position } = match pq.pop() {
80 //! None => break, // empty
84 //! // Alternatively we could have continued to find all shortest paths
85 //! if position == goal { return cost }
87 //! // Important as we may have already found a better way
88 //! if cost > dist[position] { continue }
90 //! // For each node we can reach, see if we can find a way with
91 //! // a lower cost going through this node
92 //! for edge in adj_list[position].iter() {
93 //! let next = State { cost: cost + edge.cost, position: edge.node };
95 //! // If so, add it to the frontier and continue
96 //! if next.cost < dist[next.position] {
98 //! // Relaxation, we have now found a better way
99 //! *dist.get_mut(next.position) = next.cost;
104 //! // Goal not reachable
109 //! // This is the directed graph we're going to use.
110 //! // The node numbers correspond to the different states,
111 //! // and the edge weights symbolises the cost of moving
112 //! // from one node to another.
113 //! // Note that the edges are one-way.
116 //! // +-----------------+
119 //! // 0 -----> 1 -----> 3 ---> 4
123 //! // +------> 2 -------+ |
125 //! // +---------------+
127 //! // The graph is represented as an adjacency list where each index,
128 //! // corresponding to a node value, has a list of outgoing edges.
129 //! // Chosen for it's efficiency.
130 //! let graph = vec![
132 //! vec![Edge { node: 2, cost: 10 },
133 //! Edge { node: 1, cost: 1 }],
135 //! vec![Edge { node: 3, cost: 2 }],
137 //! vec![Edge { node: 1, cost: 1 },
138 //! Edge { node: 3, cost: 3 },
139 //! Edge { node: 4, cost: 1 }],
141 //! vec![Edge { node: 0, cost: 7 },
142 //! Edge { node: 4, cost: 2 }],
146 //! assert_eq!(shortest_path(&graph, 0, 1), 1);
147 //! assert_eq!(shortest_path(&graph, 0, 3), 3);
148 //! assert_eq!(shortest_path(&graph, 3, 0), 7);
149 //! assert_eq!(shortest_path(&graph, 0, 4), 5);
150 //! assert_eq!(shortest_path(&graph, 4, 0), uint::MAX);
154 #![allow(missing_doc)]
156 use core::prelude::*;
158 use core::default::Default;
159 use core::mem::{zeroed, replace, swap};
162 use {Mutable, MutableSeq};
166 /// A priority queue implemented with a binary heap.
168 /// This will be a max-heap.
170 pub struct PriorityQueue<T> {
174 impl<T: Ord> Collection for PriorityQueue<T> {
175 /// Returns the length of the queue.
176 fn len(&self) -> uint { self.data.len() }
179 impl<T: Ord> Mutable for PriorityQueue<T> {
180 /// Drops all items from the queue.
181 fn clear(&mut self) { self.data.truncate(0) }
184 impl<T: Ord> Default for PriorityQueue<T> {
186 fn default() -> PriorityQueue<T> { PriorityQueue::new() }
189 impl<T: Ord> PriorityQueue<T> {
190 /// Creates an empty `PriorityQueue` as a max-heap.
195 /// use std::collections::PriorityQueue;
196 /// let pq: PriorityQueue<uint> = PriorityQueue::new();
198 pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
200 /// Creates an empty `PriorityQueue` with a specific capacity.
201 /// This preallocates enough memory for `capacity` elements,
202 /// so that the `PriorityQueue` does not have to be reallocated
203 /// until it contains at least that many values.
208 /// use std::collections::PriorityQueue;
209 /// let pq: PriorityQueue<uint> = PriorityQueue::with_capacity(10u);
211 pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
212 PriorityQueue { data: Vec::with_capacity(capacity) }
215 /// Creates a `PriorityQueue` from a vector. This is sometimes called
216 /// `heapifying` the vector.
221 /// use std::collections::PriorityQueue;
222 /// let pq = PriorityQueue::from_vec(vec![9i, 1, 2, 7, 3, 2]);
224 pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
225 let mut q = PriorityQueue{data: xs,};
226 let mut n = q.len() / 2;
234 /// An iterator visiting all values in underlying vector, in
240 /// use std::collections::PriorityQueue;
241 /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4]);
243 /// // Print 1, 2, 3, 4 in arbitrary order
244 /// for x in pq.iter() {
245 /// println!("{}", x);
248 pub fn iter<'a>(&'a self) -> Items<'a, T> {
249 Items { iter: self.data.iter() }
252 /// Returns the greatest item in a queue, or `None` if it is empty.
257 /// use std::collections::PriorityQueue;
259 /// let mut pq = PriorityQueue::new();
260 /// assert_eq!(pq.top(), None);
265 /// assert_eq!(pq.top(), Some(&5i));
268 pub fn top<'a>(&'a self) -> Option<&'a T> {
269 if self.is_empty() { None } else { Some(&self.data[0]) }
272 #[deprecated="renamed to `top`"]
273 pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
275 /// Returns the number of elements the queue can hold without reallocating.
280 /// use std::collections::PriorityQueue;
282 /// let pq: PriorityQueue<uint> = PriorityQueue::with_capacity(100u);
283 /// assert!(pq.capacity() >= 100u);
285 pub fn capacity(&self) -> uint { self.data.capacity() }
287 /// Reserves capacity for exactly `n` elements in the `PriorityQueue`.
288 /// Do nothing if the capacity is already sufficient.
293 /// use std::collections::PriorityQueue;
295 /// let mut pq: PriorityQueue<uint> = PriorityQueue::new();
296 /// pq.reserve_exact(100u);
297 /// assert!(pq.capacity() == 100u);
299 pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }
301 /// Reserves capacity for at least `n` elements in the `PriorityQueue`.
302 /// Do nothing if the capacity is already sufficient.
307 /// use std::collections::PriorityQueue;
309 /// let mut pq: PriorityQueue<uint> = PriorityQueue::new();
310 /// pq.reserve(100u);
311 /// assert!(pq.capacity() >= 100u);
313 pub fn reserve(&mut self, n: uint) {
317 /// Removes the greatest item from a queue and returns it, or `None` if it
323 /// use std::collections::PriorityQueue;
325 /// let mut pq = PriorityQueue::from_vec(vec![1i, 3]);
327 /// assert_eq!(pq.pop(), Some(3i));
328 /// assert_eq!(pq.pop(), Some(1i));
329 /// assert_eq!(pq.pop(), None);
331 pub fn pop(&mut self) -> Option<T> {
332 match self.data.pop() {
335 if !self.is_empty() {
336 swap(&mut item, self.data.get_mut(0));
344 #[deprecated="renamed to `pop`"]
345 pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
347 /// Pushes an item onto the queue.
352 /// use std::collections::PriorityQueue;
354 /// let mut pq = PriorityQueue::new();
359 /// assert_eq!(pq.len(), 3);
360 /// assert_eq!(pq.top(), Some(&5i));
362 pub fn push(&mut self, item: T) {
363 self.data.push(item);
364 let new_len = self.len() - 1;
365 self.siftup(0, new_len);
368 /// Pushes an item onto a queue then pops the greatest item off the queue in
369 /// an optimized fashion.
374 /// use std::collections::PriorityQueue;
376 /// let mut pq = PriorityQueue::new();
380 /// assert_eq!(pq.push_pop(3i), 5);
381 /// assert_eq!(pq.push_pop(9i), 9);
382 /// assert_eq!(pq.len(), 2);
383 /// assert_eq!(pq.top(), Some(&3i));
385 pub fn push_pop(&mut self, mut item: T) -> T {
386 if !self.is_empty() && *self.top().unwrap() > item {
387 swap(&mut item, self.data.get_mut(0));
393 /// Pops the greatest item off a queue then pushes an item onto the queue in
394 /// an optimized fashion. The push is done regardless of whether the queue
400 /// use std::collections::PriorityQueue;
402 /// let mut pq = PriorityQueue::new();
404 /// assert_eq!(pq.replace(1i), None);
405 /// assert_eq!(pq.replace(3i), Some(1i));
406 /// assert_eq!(pq.len(), 1);
407 /// assert_eq!(pq.top(), Some(&3i));
409 pub fn replace(&mut self, mut item: T) -> Option<T> {
410 if !self.is_empty() {
411 swap(&mut item, self.data.get_mut(0));
421 #[deprecated="renamed to `into_vec`"]
422 fn to_vec(self) -> Vec<T> { self.into_vec() }
425 #[deprecated="renamed to `into_sorted_vec`"]
426 fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
428 /// Consumes the `PriorityQueue` and returns the underlying vector
429 /// in arbitrary order.
434 /// use std::collections::PriorityQueue;
436 /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
437 /// let vec = pq.into_vec();
439 /// // Will print in some order
440 /// for x in vec.iter() {
441 /// println!("{}", x);
444 pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
446 /// Consumes the `PriorityQueue` and returns a vector in sorted
447 /// (ascending) order.
452 /// use std::collections::PriorityQueue;
454 /// let mut pq = PriorityQueue::from_vec(vec![1i, 2, 4, 5, 7]);
458 /// let vec = pq.into_sorted_vec();
459 /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
461 pub fn into_sorted_vec(self) -> Vec<T> {
463 let mut end = q.len();
466 q.data.as_mut_slice().swap(0, end);
467 q.siftdown_range(0, end)
472 // The implementations of siftup and siftdown use unsafe blocks in
473 // order to move an element out of the vector (leaving behind a
474 // zeroed element), shift along the others and move it back into the
475 // vector over the junk element. This reduces the constant factor
476 // compared to using swaps, which involves twice as many moves.
477 fn siftup(&mut self, start: uint, mut pos: uint) {
479 let new = replace(self.data.get_mut(pos), zeroed());
482 let parent = (pos - 1) >> 1;
483 if new > self.data[parent] {
484 let x = replace(self.data.get_mut(parent), zeroed());
485 ptr::write(self.data.get_mut(pos), x);
491 ptr::write(self.data.get_mut(pos), new);
495 fn siftdown_range(&mut self, mut pos: uint, end: uint) {
498 let new = replace(self.data.get_mut(pos), zeroed());
500 let mut child = 2 * pos + 1;
502 let right = child + 1;
503 if right < end && !(self.data[child] > self.data[right]) {
506 let x = replace(self.data.get_mut(child), zeroed());
507 ptr::write(self.data.get_mut(pos), x);
512 ptr::write(self.data.get_mut(pos), new);
513 self.siftup(start, pos);
517 fn siftdown(&mut self, pos: uint) {
518 let len = self.len();
519 self.siftdown_range(pos, len);
523 /// `PriorityQueue` iterator.
524 pub struct Items <'a, T:'a> {
525 iter: slice::Items<'a, T>,
528 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
530 fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
533 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
536 impl<T: Ord> FromIterator<T> for PriorityQueue<T> {
537 fn from_iter<Iter: Iterator<T>>(mut iter: Iter) -> PriorityQueue<T> {
538 let vec: Vec<T> = iter.collect();
539 PriorityQueue::from_vec(vec)
543 impl<T: Ord> Extendable<T> for PriorityQueue<T> {
544 fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
545 let (lower, _) = iter.size_hint();
547 let len = self.capacity();
548 self.reserve(len + lower);
560 use priority_queue::PriorityQueue;
566 let data = vec!(5i, 9, 3);
567 let iterout = [9i, 5, 3];
568 let pq = PriorityQueue::from_vec(data);
570 for el in pq.iter() {
571 assert_eq!(*el, iterout[i]);
577 fn test_top_and_pop() {
578 let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
579 let mut sorted = data.clone();
581 let mut heap = PriorityQueue::from_vec(data);
582 while !heap.is_empty() {
583 assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
584 assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
590 let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
591 assert_eq!(heap.len(), 3);
592 assert!(*heap.top().unwrap() == 9);
594 assert_eq!(heap.len(), 4);
595 assert!(*heap.top().unwrap() == 11);
597 assert_eq!(heap.len(), 5);
598 assert!(*heap.top().unwrap() == 11);
600 assert_eq!(heap.len(), 6);
601 assert!(*heap.top().unwrap() == 27);
603 assert_eq!(heap.len(), 7);
604 assert!(*heap.top().unwrap() == 27);
606 assert_eq!(heap.len(), 8);
607 assert!(*heap.top().unwrap() == 103);
611 fn test_push_unique() {
612 let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
613 assert_eq!(heap.len(), 3);
614 assert!(*heap.top().unwrap() == box 9);
616 assert_eq!(heap.len(), 4);
617 assert!(*heap.top().unwrap() == box 11);
619 assert_eq!(heap.len(), 5);
620 assert!(*heap.top().unwrap() == box 11);
622 assert_eq!(heap.len(), 6);
623 assert!(*heap.top().unwrap() == box 27);
625 assert_eq!(heap.len(), 7);
626 assert!(*heap.top().unwrap() == box 27);
628 assert_eq!(heap.len(), 8);
629 assert!(*heap.top().unwrap() == box 103);
634 let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
635 assert_eq!(heap.len(), 5);
636 assert_eq!(heap.push_pop(6), 6);
637 assert_eq!(heap.len(), 5);
638 assert_eq!(heap.push_pop(0), 5);
639 assert_eq!(heap.len(), 5);
640 assert_eq!(heap.push_pop(4), 5);
641 assert_eq!(heap.len(), 5);
642 assert_eq!(heap.push_pop(1), 4);
643 assert_eq!(heap.len(), 5);
648 let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
649 assert_eq!(heap.len(), 5);
650 assert_eq!(heap.replace(6).unwrap(), 5);
651 assert_eq!(heap.len(), 5);
652 assert_eq!(heap.replace(0).unwrap(), 6);
653 assert_eq!(heap.len(), 5);
654 assert_eq!(heap.replace(4).unwrap(), 5);
655 assert_eq!(heap.len(), 5);
656 assert_eq!(heap.replace(1).unwrap(), 4);
657 assert_eq!(heap.len(), 5);
660 fn check_to_vec(mut data: Vec<int>) {
661 let heap = PriorityQueue::from_vec(data.clone());
662 let mut v = heap.clone().into_vec();
666 assert_eq!(v.as_slice(), data.as_slice());
667 assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
672 check_to_vec(vec!());
673 check_to_vec(vec!(5i));
674 check_to_vec(vec!(3i, 2));
675 check_to_vec(vec!(2i, 3));
676 check_to_vec(vec!(5i, 1, 2));
677 check_to_vec(vec!(1i, 100, 2, 3));
678 check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
679 check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
680 check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
681 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
682 check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
683 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
684 check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
688 fn test_empty_pop() {
689 let mut heap: PriorityQueue<int> = PriorityQueue::new();
690 assert!(heap.pop().is_none());
694 fn test_empty_top() {
695 let empty: PriorityQueue<int> = PriorityQueue::new();
696 assert!(empty.top().is_none());
700 fn test_empty_replace() {
701 let mut heap: PriorityQueue<int> = PriorityQueue::new();
702 heap.replace(5).is_none();
706 fn test_from_iter() {
707 let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
709 let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
711 for &x in xs.iter() {
712 assert_eq!(q.pop().unwrap(), x);