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 `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::default::Default;
156 use core::iter::{FromIterator, IntoIterator};
157 use core::mem::{zeroed, replace, swap};
161 use vec::{self, Vec};
163 /// A priority queue implemented with a binary heap.
165 /// This will be a max-heap.
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct BinaryHeap<T> {
172 #[stable(feature = "rust1", since = "1.0.0")]
173 impl<T: Ord> Default for BinaryHeap<T> {
175 fn default() -> BinaryHeap<T> { BinaryHeap::new() }
178 impl<T: Ord> BinaryHeap<T> {
179 /// Creates an empty `BinaryHeap` as a max-heap.
184 /// use std::collections::BinaryHeap;
185 /// let mut heap = BinaryHeap::new();
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
191 /// Creates an empty `BinaryHeap` with a specific capacity.
192 /// This preallocates enough memory for `capacity` elements,
193 /// so that the `BinaryHeap` does not have to be reallocated
194 /// until it contains at least that many values.
199 /// use std::collections::BinaryHeap;
200 /// let mut heap = BinaryHeap::with_capacity(10);
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub fn with_capacity(capacity: usize) -> 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![9, 1, 2, 7, 3, 2]);
217 pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
218 let mut heap = BinaryHeap { data: vec };
219 let mut n = heap.len() / 2;
227 /// Returns an iterator visiting all values in the underlying vector, in
233 /// use std::collections::BinaryHeap;
234 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
236 /// // Print 1, 2, 3, 4 in arbitrary order
237 /// for x in heap.iter() {
238 /// println!("{}", x);
241 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn iter(&self) -> Iter<T> {
243 Iter { 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 heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
256 /// // Print 1, 2, 3, 4 in arbitrary order
257 /// for x in heap.into_iter() {
258 /// // x has type i32, not &i32
259 /// println!("{}", x);
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn into_iter(self) -> IntoIter<T> {
264 IntoIter { iter: self.data.into_iter() }
267 /// Returns the greatest item in the binary heap, or `None` if it is empty.
272 /// use std::collections::BinaryHeap;
273 /// let mut heap = BinaryHeap::new();
274 /// assert_eq!(heap.peek(), None);
279 /// assert_eq!(heap.peek(), Some(&5));
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn peek(&self) -> Option<&T> {
287 /// Returns the number of elements the binary heap can hold without reallocating.
292 /// use std::collections::BinaryHeap;
293 /// let mut heap = BinaryHeap::with_capacity(100);
294 /// assert!(heap.capacity() >= 100);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn capacity(&self) -> usize { 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 `usize`.
314 /// use std::collections::BinaryHeap;
315 /// let mut heap = BinaryHeap::new();
316 /// heap.reserve_exact(100);
317 /// assert!(heap.capacity() >= 100);
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn reserve_exact(&mut self, additional: usize) {
322 self.data.reserve_exact(additional);
325 /// Reserves capacity for at least `additional` more elements to be inserted in the
326 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
330 /// Panics if the new capacity overflows `usize`.
335 /// use std::collections::BinaryHeap;
336 /// let mut heap = BinaryHeap::new();
337 /// heap.reserve(100);
338 /// assert!(heap.capacity() >= 100);
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn reserve(&mut self, additional: usize) {
343 self.data.reserve(additional);
346 /// Discards as much additional capacity as possible.
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn shrink_to_fit(&mut self) {
349 self.data.shrink_to_fit();
352 /// Removes the greatest item from the binary heap and returns it, or `None` if it
358 /// use std::collections::BinaryHeap;
359 /// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
361 /// assert_eq!(heap.pop(), Some(3));
362 /// assert_eq!(heap.pop(), Some(1));
363 /// assert_eq!(heap.pop(), None);
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn pop(&mut self) -> Option<T> {
367 self.data.pop().map(|mut item| {
368 if !self.is_empty() {
369 swap(&mut item, &mut self.data[0]);
376 /// Pushes an item onto the binary heap.
381 /// use std::collections::BinaryHeap;
382 /// let mut heap = BinaryHeap::new();
387 /// assert_eq!(heap.len(), 3);
388 /// assert_eq!(heap.peek(), Some(&5));
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn push(&mut self, item: T) {
392 let old_len = self.len();
393 self.data.push(item);
394 self.sift_up(0, old_len);
397 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
398 /// an optimized fashion.
403 /// use std::collections::BinaryHeap;
404 /// let mut heap = BinaryHeap::new();
408 /// assert_eq!(heap.push_pop(3), 5);
409 /// assert_eq!(heap.push_pop(9), 9);
410 /// assert_eq!(heap.len(), 2);
411 /// assert_eq!(heap.peek(), Some(&3));
413 pub fn push_pop(&mut self, mut item: T) -> T {
414 match self.data.get_mut(0) {
416 Some(top) => if *top > item {
417 swap(&mut item, top);
427 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
428 /// an optimized fashion. The push is done regardless of whether the binary heap
434 /// use std::collections::BinaryHeap;
435 /// let mut heap = BinaryHeap::new();
437 /// assert_eq!(heap.replace(1), None);
438 /// assert_eq!(heap.replace(3), Some(1));
439 /// assert_eq!(heap.len(), 1);
440 /// assert_eq!(heap.peek(), Some(&3));
442 pub fn replace(&mut self, mut item: T) -> Option<T> {
443 if !self.is_empty() {
444 swap(&mut item, &mut self.data[0]);
453 /// Consumes the `BinaryHeap` and returns the underlying vector
454 /// in arbitrary order.
459 /// use std::collections::BinaryHeap;
460 /// let heap = BinaryHeap::from_vec(vec![1, 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> { self.data }
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![1, 2, 4, 5, 7]);
482 /// let vec = heap.into_sorted_vec();
483 /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7]);
485 pub fn into_sorted_vec(mut self) -> Vec<T> {
486 let mut end = self.len();
489 self.data.swap(0, end);
490 self.sift_down_range(0, end);
495 // The implementations of sift_up and sift_down use unsafe blocks in
496 // order to move an element out of the vector (leaving behind a
497 // zeroed element), shift along the others and move it back into the
498 // vector over the junk element. This reduces the constant factor
499 // compared to using swaps, which involves twice as many moves.
500 fn sift_up(&mut self, start: usize, mut pos: usize) {
502 let new = replace(&mut self.data[pos], zeroed());
505 let parent = (pos - 1) >> 1;
507 if new <= self.data[parent] { break; }
509 let x = replace(&mut self.data[parent], zeroed());
510 ptr::write(&mut self.data[pos], x);
513 ptr::write(&mut self.data[pos], new);
517 fn sift_down_range(&mut self, mut pos: usize, end: usize) {
520 let new = replace(&mut self.data[pos], zeroed());
522 let mut child = 2 * pos + 1;
524 let right = child + 1;
525 if right < end && !(self.data[child] > self.data[right]) {
528 let x = replace(&mut self.data[child], zeroed());
529 ptr::write(&mut self.data[pos], x);
534 ptr::write(&mut self.data[pos], new);
535 self.sift_up(start, pos);
539 fn sift_down(&mut self, pos: usize) {
540 let len = self.len();
541 self.sift_down_range(pos, len);
544 /// Returns the length of the binary heap.
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub fn len(&self) -> usize { self.data.len() }
548 /// Checks if the binary heap is empty.
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn is_empty(&self) -> bool { self.len() == 0 }
552 /// Clears the binary heap, returning an iterator over the removed elements.
554 #[unstable(feature = "collections",
555 reason = "matches collection reform specification, waiting for dust to settle")]
556 pub fn drain(&mut self) -> Drain<T> {
557 Drain { iter: self.data.drain() }
560 /// Drops all items from the binary heap.
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn clear(&mut self) { self.drain(); }
565 /// `BinaryHeap` iterator.
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub struct Iter <'a, T: 'a> {
568 iter: slice::Iter<'a, T>,
571 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<'a, T> Clone for Iter<'a, T> {
574 fn clone(&self) -> Iter<'a, T> {
575 Iter { iter: self.iter.clone() }
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl<'a, T> Iterator for Iter<'a, T> {
584 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
587 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
593 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
599 /// An iterator that moves out of a `BinaryHeap`.
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub struct IntoIter<T> {
602 iter: vec::IntoIter<T>,
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl<T> Iterator for IntoIter<T> {
610 fn next(&mut self) -> Option<T> { self.iter.next() }
613 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl<T> DoubleEndedIterator for IntoIter<T> {
619 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<T> ExactSizeIterator for IntoIter<T> {}
625 /// An iterator that drains a `BinaryHeap`.
626 #[unstable(feature = "collections", reason = "recent addition")]
627 pub struct Drain<'a, T: 'a> {
628 iter: vec::Drain<'a, T>,
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<'a, T: 'a> Iterator for Drain<'a, T> {
636 fn next(&mut self) -> Option<T> { self.iter.next() }
639 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
645 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
653 fn from_iter<Iter: Iterator<Item=T>>(iter: Iter) -> BinaryHeap<T> {
654 BinaryHeap::from_vec(iter.collect())
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<T: Ord> IntoIterator for BinaryHeap<T> {
661 type IntoIter = IntoIter<T>;
663 fn into_iter(self) -> IntoIter<T> {
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
671 type IntoIter = Iter<'a, T>;
673 fn into_iter(self) -> Iter<'a, T> {
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T: Ord> Extend<T> for BinaryHeap<T> {
680 fn extend<Iter: Iterator<Item=T>>(&mut self, iter: Iter) {
681 let (lower, _) = iter.size_hint();
695 use super::BinaryHeap;
699 let data = vec![5, 9, 3];
700 let iterout = [9, 5, 3];
701 let heap = BinaryHeap::from_vec(data);
704 assert_eq!(*el, iterout[i]);
710 fn test_iterator_reverse() {
711 let data = vec![5, 9, 3];
712 let iterout = vec![3, 5, 9];
713 let pq = BinaryHeap::from_vec(data);
715 let v: Vec<_> = pq.iter().rev().cloned().collect();
716 assert_eq!(v, iterout);
720 fn test_move_iter() {
721 let data = vec![5, 9, 3];
722 let iterout = vec![9, 5, 3];
723 let pq = BinaryHeap::from_vec(data);
725 let v: Vec<_> = pq.into_iter().collect();
726 assert_eq!(v, iterout);
730 fn test_move_iter_size_hint() {
731 let data = vec![5, 9];
732 let pq = BinaryHeap::from_vec(data);
734 let mut it = pq.into_iter();
736 assert_eq!(it.size_hint(), (2, Some(2)));
737 assert_eq!(it.next(), Some(9));
739 assert_eq!(it.size_hint(), (1, Some(1)));
740 assert_eq!(it.next(), Some(5));
742 assert_eq!(it.size_hint(), (0, Some(0)));
743 assert_eq!(it.next(), None);
747 fn test_move_iter_reverse() {
748 let data = vec![5, 9, 3];
749 let iterout = vec![3, 5, 9];
750 let pq = BinaryHeap::from_vec(data);
752 let v: Vec<_> = pq.into_iter().rev().collect();
753 assert_eq!(v, iterout);
757 fn test_peek_and_pop() {
758 let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];
759 let mut sorted = data.clone();
761 let mut heap = BinaryHeap::from_vec(data);
762 while !heap.is_empty() {
763 assert_eq!(heap.peek().unwrap(), sorted.last().unwrap());
764 assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
770 let mut heap = BinaryHeap::from_vec(vec![2, 4, 9]);
771 assert_eq!(heap.len(), 3);
772 assert!(*heap.peek().unwrap() == 9);
774 assert_eq!(heap.len(), 4);
775 assert!(*heap.peek().unwrap() == 11);
777 assert_eq!(heap.len(), 5);
778 assert!(*heap.peek().unwrap() == 11);
780 assert_eq!(heap.len(), 6);
781 assert!(*heap.peek().unwrap() == 27);
783 assert_eq!(heap.len(), 7);
784 assert!(*heap.peek().unwrap() == 27);
786 assert_eq!(heap.len(), 8);
787 assert!(*heap.peek().unwrap() == 103);
791 fn test_push_unique() {
792 let mut heap = BinaryHeap::from_vec(vec![box 2, box 4, box 9]);
793 assert_eq!(heap.len(), 3);
794 assert!(*heap.peek().unwrap() == box 9);
796 assert_eq!(heap.len(), 4);
797 assert!(*heap.peek().unwrap() == box 11);
799 assert_eq!(heap.len(), 5);
800 assert!(*heap.peek().unwrap() == box 11);
802 assert_eq!(heap.len(), 6);
803 assert!(*heap.peek().unwrap() == box 27);
805 assert_eq!(heap.len(), 7);
806 assert!(*heap.peek().unwrap() == box 27);
808 assert_eq!(heap.len(), 8);
809 assert!(*heap.peek().unwrap() == box 103);
814 let mut heap = BinaryHeap::from_vec(vec![5, 5, 2, 1, 3]);
815 assert_eq!(heap.len(), 5);
816 assert_eq!(heap.push_pop(6), 6);
817 assert_eq!(heap.len(), 5);
818 assert_eq!(heap.push_pop(0), 5);
819 assert_eq!(heap.len(), 5);
820 assert_eq!(heap.push_pop(4), 5);
821 assert_eq!(heap.len(), 5);
822 assert_eq!(heap.push_pop(1), 4);
823 assert_eq!(heap.len(), 5);
828 let mut heap = BinaryHeap::from_vec(vec![5, 5, 2, 1, 3]);
829 assert_eq!(heap.len(), 5);
830 assert_eq!(heap.replace(6).unwrap(), 5);
831 assert_eq!(heap.len(), 5);
832 assert_eq!(heap.replace(0).unwrap(), 6);
833 assert_eq!(heap.len(), 5);
834 assert_eq!(heap.replace(4).unwrap(), 5);
835 assert_eq!(heap.len(), 5);
836 assert_eq!(heap.replace(1).unwrap(), 4);
837 assert_eq!(heap.len(), 5);
840 fn check_to_vec(mut data: Vec<i32>) {
841 let heap = BinaryHeap::from_vec(data.clone());
842 let mut v = heap.clone().into_vec();
847 assert_eq!(heap.into_sorted_vec(), data);
852 check_to_vec(vec![]);
853 check_to_vec(vec![5]);
854 check_to_vec(vec![3, 2]);
855 check_to_vec(vec![2, 3]);
856 check_to_vec(vec![5, 1, 2]);
857 check_to_vec(vec![1, 100, 2, 3]);
858 check_to_vec(vec![1, 3, 5, 7, 9, 2, 4, 6, 8, 0]);
859 check_to_vec(vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1]);
860 check_to_vec(vec![9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0]);
861 check_to_vec(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
862 check_to_vec(vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
863 check_to_vec(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2]);
864 check_to_vec(vec![5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]);
868 fn test_empty_pop() {
869 let mut heap = BinaryHeap::<i32>::new();
870 assert!(heap.pop().is_none());
874 fn test_empty_peek() {
875 let empty = BinaryHeap::<i32>::new();
876 assert!(empty.peek().is_none());
880 fn test_empty_replace() {
881 let mut heap = BinaryHeap::new();
882 assert!(heap.replace(5).is_none());
886 fn test_from_iter() {
887 let xs = vec![9, 8, 7, 6, 5, 4, 3, 2, 1];
889 let mut q: BinaryHeap<_> = xs.iter().rev().cloned().collect();
892 assert_eq!(q.pop().unwrap(), x);
898 let mut q: BinaryHeap<_> = [9, 8, 7, 6, 5, 4, 3, 2, 1].iter().cloned().collect();
900 assert_eq!(q.drain().take(5).count(), 5);
902 assert!(q.is_empty());