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 #![allow(missing_doc)]
17 use core::default::Default;
18 use core::mem::{zeroed, replace, swap};
21 use {Collection, Mutable};
25 /// A priority queue implemented with a binary heap
27 pub struct PriorityQueue<T> {
31 impl<T: Ord> Collection for PriorityQueue<T> {
32 /// Returns the length of the queue
33 fn len(&self) -> uint { self.data.len() }
36 impl<T: Ord> Mutable for PriorityQueue<T> {
37 /// Drop all items from the queue
38 fn clear(&mut self) { self.data.truncate(0) }
41 impl<T: Ord> Default for PriorityQueue<T> {
43 fn default() -> PriorityQueue<T> { PriorityQueue::new() }
46 impl<T: Ord> PriorityQueue<T> {
47 /// An iterator visiting all values in underlying vector, in
49 pub fn iter<'a>(&'a self) -> Items<'a, T> {
50 Items { iter: self.data.iter() }
53 /// Returns the greatest item in a queue or None if it is empty
54 pub fn top<'a>(&'a self) -> Option<&'a T> {
55 if self.is_empty() { None } else { Some(self.data.get(0)) }
58 #[deprecated="renamed to `top`"]
59 pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
61 /// Returns the number of elements the queue can hold without reallocating
62 pub fn capacity(&self) -> uint { self.data.capacity() }
64 /// Reserve capacity for exactly n elements in the PriorityQueue.
65 /// Do nothing if the capacity is already sufficient.
66 pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }
68 /// Reserve capacity for at least n elements in the PriorityQueue.
69 /// Do nothing if the capacity is already sufficient.
70 pub fn reserve(&mut self, n: uint) {
74 /// Remove the greatest item from a queue and return it, or `None` if it is
76 pub fn pop(&mut self) -> Option<T> {
77 match self.data.pop() {
81 swap(&mut item, self.data.get_mut(0));
89 #[deprecated="renamed to `pop`"]
90 pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
92 /// Push an item onto the queue
93 pub fn push(&mut self, item: T) {
95 let new_len = self.len() - 1;
96 self.siftup(0, new_len);
99 /// Optimized version of a push followed by a pop
100 pub fn push_pop(&mut self, mut item: T) -> T {
101 if !self.is_empty() && *self.top().unwrap() > item {
102 swap(&mut item, self.data.get_mut(0));
108 /// Optimized version of a pop followed by a push. The push is done
109 /// regardless of whether the queue is empty.
110 pub fn replace(&mut self, mut item: T) -> Option<T> {
111 if !self.is_empty() {
112 swap(&mut item, self.data.get_mut(0));
122 #[deprecated="renamed to `into_vec`"]
123 fn to_vec(self) -> Vec<T> { self.into_vec() }
126 #[deprecated="renamed to `into_sorted_vec`"]
127 fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
129 /// Consume the PriorityQueue and return the underlying vector
130 pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
132 /// Consume the PriorityQueue and return a vector in sorted
133 /// (ascending) order
134 pub fn into_sorted_vec(self) -> Vec<T> {
136 let mut end = q.len();
139 q.data.as_mut_slice().swap(0, end);
140 q.siftdown_range(0, end)
145 /// Create an empty PriorityQueue
146 pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
148 /// Create an empty PriorityQueue with capacity `capacity`
149 pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
150 PriorityQueue { data: Vec::with_capacity(capacity) }
153 /// Create a PriorityQueue from a vector (heapify)
154 pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
155 let mut q = PriorityQueue{data: xs,};
156 let mut n = q.len() / 2;
164 // The implementations of siftup and siftdown use unsafe blocks in
165 // order to move an element out of the vector (leaving behind a
166 // zeroed element), shift along the others and move it back into the
167 // vector over the junk element. This reduces the constant factor
168 // compared to using swaps, which involves twice as many moves.
169 fn siftup(&mut self, start: uint, mut pos: uint) {
171 let new = replace(self.data.get_mut(pos), zeroed());
174 let parent = (pos - 1) >> 1;
175 if new > *self.data.get(parent) {
176 let x = replace(self.data.get_mut(parent), zeroed());
177 ptr::write(self.data.get_mut(pos), x);
183 ptr::write(self.data.get_mut(pos), new);
187 fn siftdown_range(&mut self, mut pos: uint, end: uint) {
190 let new = replace(self.data.get_mut(pos), zeroed());
192 let mut child = 2 * pos + 1;
194 let right = child + 1;
195 if right < end && !(*self.data.get(child) > *self.data.get(right)) {
198 let x = replace(self.data.get_mut(child), zeroed());
199 ptr::write(self.data.get_mut(pos), x);
204 ptr::write(self.data.get_mut(pos), new);
205 self.siftup(start, pos);
209 fn siftdown(&mut self, pos: uint) {
210 let len = self.len();
211 self.siftdown_range(pos, len);
215 /// PriorityQueue iterator
216 pub struct Items <'a, T> {
217 iter: slice::Items<'a, T>,
220 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
222 fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
225 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
228 impl<T: Ord> FromIterator<T> for PriorityQueue<T> {
229 fn from_iter<Iter: Iterator<T>>(iter: Iter) -> PriorityQueue<T> {
230 let mut q = PriorityQueue::new();
236 impl<T: Ord> Extendable<T> for PriorityQueue<T> {
237 fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
238 let (lower, _) = iter.size_hint();
240 let len = self.capacity();
241 self.reserve(len + lower);
253 use priority_queue::PriorityQueue;
258 let data = vec!(5i, 9, 3);
259 let iterout = [9i, 5, 3];
260 let pq = PriorityQueue::from_vec(data);
262 for el in pq.iter() {
263 assert_eq!(*el, iterout[i]);
269 fn test_top_and_pop() {
270 let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
271 let mut sorted = data.clone();
273 let mut heap = PriorityQueue::from_vec(data);
274 while !heap.is_empty() {
275 assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
276 assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
282 let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
283 assert_eq!(heap.len(), 3);
284 assert!(*heap.top().unwrap() == 9);
286 assert_eq!(heap.len(), 4);
287 assert!(*heap.top().unwrap() == 11);
289 assert_eq!(heap.len(), 5);
290 assert!(*heap.top().unwrap() == 11);
292 assert_eq!(heap.len(), 6);
293 assert!(*heap.top().unwrap() == 27);
295 assert_eq!(heap.len(), 7);
296 assert!(*heap.top().unwrap() == 27);
298 assert_eq!(heap.len(), 8);
299 assert!(*heap.top().unwrap() == 103);
303 fn test_push_unique() {
304 let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
305 assert_eq!(heap.len(), 3);
306 assert!(*heap.top().unwrap() == box 9);
308 assert_eq!(heap.len(), 4);
309 assert!(*heap.top().unwrap() == box 11);
311 assert_eq!(heap.len(), 5);
312 assert!(*heap.top().unwrap() == box 11);
314 assert_eq!(heap.len(), 6);
315 assert!(*heap.top().unwrap() == box 27);
317 assert_eq!(heap.len(), 7);
318 assert!(*heap.top().unwrap() == box 27);
320 assert_eq!(heap.len(), 8);
321 assert!(*heap.top().unwrap() == box 103);
326 let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
327 assert_eq!(heap.len(), 5);
328 assert_eq!(heap.push_pop(6), 6);
329 assert_eq!(heap.len(), 5);
330 assert_eq!(heap.push_pop(0), 5);
331 assert_eq!(heap.len(), 5);
332 assert_eq!(heap.push_pop(4), 5);
333 assert_eq!(heap.len(), 5);
334 assert_eq!(heap.push_pop(1), 4);
335 assert_eq!(heap.len(), 5);
340 let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
341 assert_eq!(heap.len(), 5);
342 assert_eq!(heap.replace(6).unwrap(), 5);
343 assert_eq!(heap.len(), 5);
344 assert_eq!(heap.replace(0).unwrap(), 6);
345 assert_eq!(heap.len(), 5);
346 assert_eq!(heap.replace(4).unwrap(), 5);
347 assert_eq!(heap.len(), 5);
348 assert_eq!(heap.replace(1).unwrap(), 4);
349 assert_eq!(heap.len(), 5);
352 fn check_to_vec(mut data: Vec<int>) {
353 let heap = PriorityQueue::from_vec(data.clone());
354 let mut v = heap.clone().into_vec();
358 assert_eq!(v.as_slice(), data.as_slice());
359 assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
364 check_to_vec(vec!());
365 check_to_vec(vec!(5i));
366 check_to_vec(vec!(3i, 2));
367 check_to_vec(vec!(2i, 3));
368 check_to_vec(vec!(5i, 1, 2));
369 check_to_vec(vec!(1i, 100, 2, 3));
370 check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
371 check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
372 check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
373 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
374 check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
375 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
376 check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
380 fn test_empty_pop() {
381 let mut heap: PriorityQueue<int> = PriorityQueue::new();
382 assert!(heap.pop().is_none());
386 fn test_empty_top() {
387 let empty: PriorityQueue<int> = PriorityQueue::new();
388 assert!(empty.top().is_none());
392 fn test_empty_replace() {
393 let mut heap: PriorityQueue<int> = PriorityQueue::new();
394 heap.replace(5).is_none();
398 fn test_from_iter() {
399 let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
401 let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
403 for &x in xs.iter() {
404 assert_eq!(q.pop().unwrap(), x);