]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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. | |
4 | // | |
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. | |
10 | ||
11 | //! A priority queue implemented with a binary heap. | |
12 | //! | |
62682a34 SL |
13 | //! Insertion and popping the largest element have `O(log n)` time complexity. |
14 | //! Checking the largest element is `O(1)`. Converting a vector to a binary heap | |
15 | //! can be done in-place, and has `O(n)` complexity. A binary heap can also be | |
16 | //! converted to a sorted vector in-place, allowing it to be used for an `O(n | |
17 | //! log n)` in-place heapsort. | |
1a4d82fc JJ |
18 | //! |
19 | //! # Examples | |
20 | //! | |
21 | //! This is a larger example that implements [Dijkstra's algorithm][dijkstra] | |
22 | //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph]. | |
23 | //! It shows how to use `BinaryHeap` with custom types. | |
24 | //! | |
25 | //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm | |
26 | //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem | |
27 | //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph | |
28 | //! | |
29 | //! ``` | |
30 | //! use std::cmp::Ordering; | |
31 | //! use std::collections::BinaryHeap; | |
85aaf69f | 32 | //! use std::usize; |
1a4d82fc | 33 | //! |
c34b1796 | 34 | //! #[derive(Copy, Clone, Eq, PartialEq)] |
1a4d82fc | 35 | //! struct State { |
85aaf69f SL |
36 | //! cost: usize, |
37 | //! position: usize, | |
1a4d82fc JJ |
38 | //! } |
39 | //! | |
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) | |
47 | //! } | |
48 | //! } | |
49 | //! | |
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)) | |
54 | //! } | |
55 | //! } | |
56 | //! | |
85aaf69f | 57 | //! // Each node is represented as an `usize`, for a shorter implementation. |
1a4d82fc | 58 | //! struct Edge { |
85aaf69f SL |
59 | //! node: usize, |
60 | //! cost: usize, | |
1a4d82fc JJ |
61 | //! } |
62 | //! | |
63 | //! // Dijkstra's shortest path algorithm. | |
64 | //! | |
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 | |
85aaf69f | 67 | //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value, |
1a4d82fc | 68 | //! // for a simpler implementation. |
9cc50fc6 | 69 | //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> { |
1a4d82fc | 70 | //! // dist[node] = current shortest distance from `start` to `node` |
85aaf69f | 71 | //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect(); |
1a4d82fc JJ |
72 | //! |
73 | //! let mut heap = BinaryHeap::new(); | |
74 | //! | |
75 | //! // We're at `start`, with a zero cost | |
76 | //! dist[start] = 0; | |
77 | //! heap.push(State { cost: 0, position: start }); | |
78 | //! | |
79 | //! // Examine the frontier with lower cost nodes first (min-heap) | |
80 | //! while let Some(State { cost, position }) = heap.pop() { | |
81 | //! // Alternatively we could have continued to find all shortest paths | |
9cc50fc6 | 82 | //! if position == goal { return Some(cost); } |
1a4d82fc JJ |
83 | //! |
84 | //! // Important as we may have already found a better way | |
85 | //! if cost > dist[position] { continue; } | |
86 | //! | |
87 | //! // For each node we can reach, see if we can find a way with | |
88 | //! // a lower cost going through this node | |
62682a34 | 89 | //! for edge in &adj_list[position] { |
1a4d82fc JJ |
90 | //! let next = State { cost: cost + edge.cost, position: edge.node }; |
91 | //! | |
92 | //! // If so, add it to the frontier and continue | |
93 | //! if next.cost < dist[next.position] { | |
94 | //! heap.push(next); | |
95 | //! // Relaxation, we have now found a better way | |
96 | //! dist[next.position] = next.cost; | |
97 | //! } | |
98 | //! } | |
99 | //! } | |
100 | //! | |
101 | //! // Goal not reachable | |
9cc50fc6 | 102 | //! None |
1a4d82fc JJ |
103 | //! } |
104 | //! | |
105 | //! fn main() { | |
106 | //! // This is the directed graph we're going to use. | |
107 | //! // The node numbers correspond to the different states, | |
108 | //! // and the edge weights symbolize the cost of moving | |
109 | //! // from one node to another. | |
110 | //! // Note that the edges are one-way. | |
111 | //! // | |
112 | //! // 7 | |
113 | //! // +-----------------+ | |
114 | //! // | | | |
e9174d1e | 115 | //! // v 1 2 | 2 |
1a4d82fc JJ |
116 | //! // 0 -----> 1 -----> 3 ---> 4 |
117 | //! // | ^ ^ ^ | |
118 | //! // | | 1 | | | |
119 | //! // | | | 3 | 1 | |
120 | //! // +------> 2 -------+ | | |
121 | //! // 10 | | | |
122 | //! // +---------------+ | |
123 | //! // | |
124 | //! // The graph is represented as an adjacency list where each index, | |
125 | //! // corresponding to a node value, has a list of outgoing edges. | |
126 | //! // Chosen for its efficiency. | |
127 | //! let graph = vec![ | |
128 | //! // Node 0 | |
129 | //! vec![Edge { node: 2, cost: 10 }, | |
130 | //! Edge { node: 1, cost: 1 }], | |
131 | //! // Node 1 | |
132 | //! vec![Edge { node: 3, cost: 2 }], | |
133 | //! // Node 2 | |
134 | //! vec![Edge { node: 1, cost: 1 }, | |
135 | //! Edge { node: 3, cost: 3 }, | |
136 | //! Edge { node: 4, cost: 1 }], | |
137 | //! // Node 3 | |
138 | //! vec![Edge { node: 0, cost: 7 }, | |
139 | //! Edge { node: 4, cost: 2 }], | |
140 | //! // Node 4 | |
141 | //! vec![]]; | |
142 | //! | |
9cc50fc6 SL |
143 | //! assert_eq!(shortest_path(&graph, 0, 1), Some(1)); |
144 | //! assert_eq!(shortest_path(&graph, 0, 3), Some(3)); | |
145 | //! assert_eq!(shortest_path(&graph, 3, 0), Some(7)); | |
146 | //! assert_eq!(shortest_path(&graph, 0, 4), Some(5)); | |
147 | //! assert_eq!(shortest_path(&graph, 4, 0), None); | |
1a4d82fc JJ |
148 | //! } |
149 | //! ``` | |
150 | ||
151 | #![allow(missing_docs)] | |
85aaf69f | 152 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 153 | |
92a42be0 | 154 | use core::iter::FromIterator; |
d9579d0f | 155 | use core::mem::swap; |
1a4d82fc | 156 | use core::ptr; |
e9174d1e | 157 | use core::fmt; |
1a4d82fc JJ |
158 | |
159 | use slice; | |
160 | use vec::{self, Vec}; | |
161 | ||
162 | /// A priority queue implemented with a binary heap. | |
163 | /// | |
164 | /// This will be a max-heap. | |
c34b1796 AL |
165 | /// |
166 | /// It is a logic error for an item to be modified in such a way that the | |
167 | /// item's ordering relative to any other item, as determined by the `Ord` | |
168 | /// trait, changes while it is in the heap. This is normally only possible | |
169 | /// through `Cell`, `RefCell`, global state, I/O, or unsafe code. | |
54a0048b SL |
170 | /// |
171 | /// # Examples | |
172 | /// | |
173 | /// ``` | |
174 | /// use std::collections::BinaryHeap; | |
175 | /// | |
176 | /// // Type inference lets us omit an explicit type signature (which | |
177 | /// // would be `BinaryHeap<i32>` in this example). | |
178 | /// let mut heap = BinaryHeap::new(); | |
179 | /// | |
180 | /// // We can use peek to look at the next item in the heap. In this case, | |
181 | /// // there's no items in there yet so we get None. | |
182 | /// assert_eq!(heap.peek(), None); | |
183 | /// | |
184 | /// // Let's add some scores... | |
185 | /// heap.push(1); | |
186 | /// heap.push(5); | |
187 | /// heap.push(2); | |
188 | /// | |
189 | /// // Now peek shows the most important item in the heap. | |
190 | /// assert_eq!(heap.peek(), Some(&5)); | |
191 | /// | |
192 | /// // We can check the length of a heap. | |
193 | /// assert_eq!(heap.len(), 3); | |
194 | /// | |
195 | /// // We can iterate over the items in the heap, although they are returned in | |
196 | /// // a random order. | |
197 | /// for x in &heap { | |
198 | /// println!("{}", x); | |
199 | /// } | |
200 | /// | |
201 | /// // If we instead pop these scores, they should come back in order. | |
202 | /// assert_eq!(heap.pop(), Some(5)); | |
203 | /// assert_eq!(heap.pop(), Some(2)); | |
204 | /// assert_eq!(heap.pop(), Some(1)); | |
205 | /// assert_eq!(heap.pop(), None); | |
206 | /// | |
207 | /// // We can clear the heap of any remaining items. | |
208 | /// heap.clear(); | |
209 | /// | |
210 | /// // The heap should now be empty. | |
211 | /// assert!(heap.is_empty()) | |
212 | /// ``` | |
85aaf69f | 213 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
214 | pub struct BinaryHeap<T> { |
215 | data: Vec<T>, | |
216 | } | |
217 | ||
b039eaaf SL |
218 | #[stable(feature = "rust1", since = "1.0.0")] |
219 | impl<T: Clone> Clone for BinaryHeap<T> { | |
220 | fn clone(&self) -> Self { | |
221 | BinaryHeap { data: self.data.clone() } | |
222 | } | |
223 | ||
224 | fn clone_from(&mut self, source: &Self) { | |
225 | self.data.clone_from(&source.data); | |
226 | } | |
227 | } | |
228 | ||
85aaf69f | 229 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
230 | impl<T: Ord> Default for BinaryHeap<T> { |
231 | #[inline] | |
92a42be0 SL |
232 | fn default() -> BinaryHeap<T> { |
233 | BinaryHeap::new() | |
234 | } | |
1a4d82fc JJ |
235 | } |
236 | ||
e9174d1e SL |
237 | #[stable(feature = "binaryheap_debug", since = "1.4.0")] |
238 | impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> { | |
239 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
240 | f.debug_list().entries(self.iter()).finish() | |
241 | } | |
242 | } | |
243 | ||
1a4d82fc JJ |
244 | impl<T: Ord> BinaryHeap<T> { |
245 | /// Creates an empty `BinaryHeap` as a max-heap. | |
246 | /// | |
247 | /// # Examples | |
248 | /// | |
54a0048b SL |
249 | /// Basic usage: |
250 | /// | |
1a4d82fc JJ |
251 | /// ``` |
252 | /// use std::collections::BinaryHeap; | |
253 | /// let mut heap = BinaryHeap::new(); | |
85aaf69f | 254 | /// heap.push(4); |
1a4d82fc | 255 | /// ``` |
85aaf69f | 256 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
257 | pub fn new() -> BinaryHeap<T> { |
258 | BinaryHeap { data: vec![] } | |
259 | } | |
1a4d82fc JJ |
260 | |
261 | /// Creates an empty `BinaryHeap` with a specific capacity. | |
262 | /// This preallocates enough memory for `capacity` elements, | |
263 | /// so that the `BinaryHeap` does not have to be reallocated | |
264 | /// until it contains at least that many values. | |
265 | /// | |
266 | /// # Examples | |
267 | /// | |
54a0048b SL |
268 | /// Basic usage: |
269 | /// | |
1a4d82fc JJ |
270 | /// ``` |
271 | /// use std::collections::BinaryHeap; | |
272 | /// let mut heap = BinaryHeap::with_capacity(10); | |
85aaf69f | 273 | /// heap.push(4); |
1a4d82fc | 274 | /// ``` |
85aaf69f SL |
275 | #[stable(feature = "rust1", since = "1.0.0")] |
276 | pub fn with_capacity(capacity: usize) -> BinaryHeap<T> { | |
1a4d82fc JJ |
277 | BinaryHeap { data: Vec::with_capacity(capacity) } |
278 | } | |
279 | ||
1a4d82fc JJ |
280 | /// Returns an iterator visiting all values in the underlying vector, in |
281 | /// arbitrary order. | |
282 | /// | |
283 | /// # Examples | |
284 | /// | |
54a0048b SL |
285 | /// Basic usage: |
286 | /// | |
1a4d82fc JJ |
287 | /// ``` |
288 | /// use std::collections::BinaryHeap; | |
b039eaaf | 289 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]); |
1a4d82fc JJ |
290 | /// |
291 | /// // Print 1, 2, 3, 4 in arbitrary order | |
292 | /// for x in heap.iter() { | |
293 | /// println!("{}", x); | |
294 | /// } | |
295 | /// ``` | |
85aaf69f | 296 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
297 | pub fn iter(&self) -> Iter<T> { |
298 | Iter { iter: self.data.iter() } | |
299 | } | |
300 | ||
1a4d82fc JJ |
301 | /// Returns the greatest item in the binary heap, or `None` if it is empty. |
302 | /// | |
303 | /// # Examples | |
304 | /// | |
54a0048b SL |
305 | /// Basic usage: |
306 | /// | |
1a4d82fc JJ |
307 | /// ``` |
308 | /// use std::collections::BinaryHeap; | |
309 | /// let mut heap = BinaryHeap::new(); | |
310 | /// assert_eq!(heap.peek(), None); | |
311 | /// | |
85aaf69f | 312 | /// heap.push(1); |
1a4d82fc JJ |
313 | /// heap.push(5); |
314 | /// heap.push(2); | |
315 | /// assert_eq!(heap.peek(), Some(&5)); | |
316 | /// | |
317 | /// ``` | |
85aaf69f | 318 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
319 | pub fn peek(&self) -> Option<&T> { |
320 | self.data.get(0) | |
321 | } | |
322 | ||
323 | /// Returns the number of elements the binary heap can hold without reallocating. | |
324 | /// | |
325 | /// # Examples | |
326 | /// | |
54a0048b SL |
327 | /// Basic usage: |
328 | /// | |
1a4d82fc JJ |
329 | /// ``` |
330 | /// use std::collections::BinaryHeap; | |
331 | /// let mut heap = BinaryHeap::with_capacity(100); | |
332 | /// assert!(heap.capacity() >= 100); | |
85aaf69f | 333 | /// heap.push(4); |
1a4d82fc | 334 | /// ``` |
85aaf69f | 335 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
336 | pub fn capacity(&self) -> usize { |
337 | self.data.capacity() | |
338 | } | |
1a4d82fc JJ |
339 | |
340 | /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the | |
341 | /// given `BinaryHeap`. Does nothing if the capacity is already sufficient. | |
342 | /// | |
343 | /// Note that the allocator may give the collection more space than it requests. Therefore | |
344 | /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future | |
345 | /// insertions are expected. | |
346 | /// | |
347 | /// # Panics | |
348 | /// | |
85aaf69f | 349 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
350 | /// |
351 | /// # Examples | |
352 | /// | |
54a0048b SL |
353 | /// Basic usage: |
354 | /// | |
1a4d82fc JJ |
355 | /// ``` |
356 | /// use std::collections::BinaryHeap; | |
357 | /// let mut heap = BinaryHeap::new(); | |
358 | /// heap.reserve_exact(100); | |
359 | /// assert!(heap.capacity() >= 100); | |
85aaf69f | 360 | /// heap.push(4); |
1a4d82fc | 361 | /// ``` |
85aaf69f SL |
362 | #[stable(feature = "rust1", since = "1.0.0")] |
363 | pub fn reserve_exact(&mut self, additional: usize) { | |
1a4d82fc JJ |
364 | self.data.reserve_exact(additional); |
365 | } | |
366 | ||
367 | /// Reserves capacity for at least `additional` more elements to be inserted in the | |
368 | /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations. | |
369 | /// | |
370 | /// # Panics | |
371 | /// | |
85aaf69f | 372 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
373 | /// |
374 | /// # Examples | |
375 | /// | |
54a0048b SL |
376 | /// Basic usage: |
377 | /// | |
1a4d82fc JJ |
378 | /// ``` |
379 | /// use std::collections::BinaryHeap; | |
380 | /// let mut heap = BinaryHeap::new(); | |
381 | /// heap.reserve(100); | |
382 | /// assert!(heap.capacity() >= 100); | |
85aaf69f | 383 | /// heap.push(4); |
1a4d82fc | 384 | /// ``` |
85aaf69f SL |
385 | #[stable(feature = "rust1", since = "1.0.0")] |
386 | pub fn reserve(&mut self, additional: usize) { | |
1a4d82fc JJ |
387 | self.data.reserve(additional); |
388 | } | |
389 | ||
390 | /// Discards as much additional capacity as possible. | |
54a0048b SL |
391 | /// |
392 | /// # Examples | |
393 | /// | |
394 | /// Basic usage: | |
395 | /// | |
396 | /// ``` | |
397 | /// use std::collections::BinaryHeap; | |
398 | /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100); | |
399 | /// | |
400 | /// assert!(heap.capacity() >= 100); | |
401 | /// heap.shrink_to_fit(); | |
402 | /// assert!(heap.capacity() == 0); | |
403 | /// ``` | |
85aaf69f | 404 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
405 | pub fn shrink_to_fit(&mut self) { |
406 | self.data.shrink_to_fit(); | |
407 | } | |
408 | ||
409 | /// Removes the greatest item from the binary heap and returns it, or `None` if it | |
410 | /// is empty. | |
411 | /// | |
412 | /// # Examples | |
413 | /// | |
54a0048b SL |
414 | /// Basic usage: |
415 | /// | |
1a4d82fc JJ |
416 | /// ``` |
417 | /// use std::collections::BinaryHeap; | |
b039eaaf | 418 | /// let mut heap = BinaryHeap::from(vec![1, 3]); |
1a4d82fc JJ |
419 | /// |
420 | /// assert_eq!(heap.pop(), Some(3)); | |
421 | /// assert_eq!(heap.pop(), Some(1)); | |
422 | /// assert_eq!(heap.pop(), None); | |
423 | /// ``` | |
85aaf69f | 424 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
425 | pub fn pop(&mut self) -> Option<T> { |
426 | self.data.pop().map(|mut item| { | |
427 | if !self.is_empty() { | |
428 | swap(&mut item, &mut self.data[0]); | |
9cc50fc6 | 429 | self.sift_down_to_bottom(0); |
1a4d82fc JJ |
430 | } |
431 | item | |
432 | }) | |
433 | } | |
434 | ||
435 | /// Pushes an item onto the binary heap. | |
436 | /// | |
437 | /// # Examples | |
438 | /// | |
54a0048b SL |
439 | /// Basic usage: |
440 | /// | |
1a4d82fc JJ |
441 | /// ``` |
442 | /// use std::collections::BinaryHeap; | |
443 | /// let mut heap = BinaryHeap::new(); | |
85aaf69f | 444 | /// heap.push(3); |
1a4d82fc JJ |
445 | /// heap.push(5); |
446 | /// heap.push(1); | |
447 | /// | |
448 | /// assert_eq!(heap.len(), 3); | |
449 | /// assert_eq!(heap.peek(), Some(&5)); | |
450 | /// ``` | |
85aaf69f | 451 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
452 | pub fn push(&mut self, item: T) { |
453 | let old_len = self.len(); | |
454 | self.data.push(item); | |
455 | self.sift_up(0, old_len); | |
456 | } | |
457 | ||
458 | /// Pushes an item onto the binary heap, then pops the greatest item off the queue in | |
459 | /// an optimized fashion. | |
460 | /// | |
461 | /// # Examples | |
462 | /// | |
54a0048b SL |
463 | /// Basic usage: |
464 | /// | |
1a4d82fc | 465 | /// ``` |
e9174d1e | 466 | /// #![feature(binary_heap_extras)] |
c1a9b12d | 467 | /// |
1a4d82fc JJ |
468 | /// use std::collections::BinaryHeap; |
469 | /// let mut heap = BinaryHeap::new(); | |
85aaf69f | 470 | /// heap.push(1); |
1a4d82fc JJ |
471 | /// heap.push(5); |
472 | /// | |
473 | /// assert_eq!(heap.push_pop(3), 5); | |
474 | /// assert_eq!(heap.push_pop(9), 9); | |
475 | /// assert_eq!(heap.len(), 2); | |
476 | /// assert_eq!(heap.peek(), Some(&3)); | |
477 | /// ``` | |
e9174d1e SL |
478 | #[unstable(feature = "binary_heap_extras", |
479 | reason = "needs to be audited", | |
480 | issue = "28147")] | |
1a4d82fc JJ |
481 | pub fn push_pop(&mut self, mut item: T) -> T { |
482 | match self.data.get_mut(0) { | |
483 | None => return item, | |
92a42be0 SL |
484 | Some(top) => { |
485 | if *top > item { | |
486 | swap(&mut item, top); | |
487 | } else { | |
488 | return item; | |
489 | } | |
490 | } | |
1a4d82fc JJ |
491 | } |
492 | ||
493 | self.sift_down(0); | |
494 | item | |
495 | } | |
496 | ||
497 | /// Pops the greatest item off the binary heap, then pushes an item onto the queue in | |
498 | /// an optimized fashion. The push is done regardless of whether the binary heap | |
499 | /// was empty. | |
500 | /// | |
501 | /// # Examples | |
502 | /// | |
54a0048b SL |
503 | /// Basic usage: |
504 | /// | |
1a4d82fc | 505 | /// ``` |
e9174d1e | 506 | /// #![feature(binary_heap_extras)] |
c1a9b12d | 507 | /// |
1a4d82fc JJ |
508 | /// use std::collections::BinaryHeap; |
509 | /// let mut heap = BinaryHeap::new(); | |
510 | /// | |
85aaf69f | 511 | /// assert_eq!(heap.replace(1), None); |
1a4d82fc JJ |
512 | /// assert_eq!(heap.replace(3), Some(1)); |
513 | /// assert_eq!(heap.len(), 1); | |
514 | /// assert_eq!(heap.peek(), Some(&3)); | |
515 | /// ``` | |
e9174d1e SL |
516 | #[unstable(feature = "binary_heap_extras", |
517 | reason = "needs to be audited", | |
518 | issue = "28147")] | |
1a4d82fc JJ |
519 | pub fn replace(&mut self, mut item: T) -> Option<T> { |
520 | if !self.is_empty() { | |
521 | swap(&mut item, &mut self.data[0]); | |
522 | self.sift_down(0); | |
523 | Some(item) | |
524 | } else { | |
525 | self.push(item); | |
526 | None | |
527 | } | |
528 | } | |
529 | ||
530 | /// Consumes the `BinaryHeap` and returns the underlying vector | |
531 | /// in arbitrary order. | |
532 | /// | |
533 | /// # Examples | |
534 | /// | |
54a0048b SL |
535 | /// Basic usage: |
536 | /// | |
1a4d82fc JJ |
537 | /// ``` |
538 | /// use std::collections::BinaryHeap; | |
b039eaaf | 539 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]); |
1a4d82fc JJ |
540 | /// let vec = heap.into_vec(); |
541 | /// | |
542 | /// // Will print in some order | |
62682a34 | 543 | /// for x in vec { |
1a4d82fc JJ |
544 | /// println!("{}", x); |
545 | /// } | |
546 | /// ``` | |
b039eaaf SL |
547 | #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] |
548 | pub fn into_vec(self) -> Vec<T> { | |
549 | self.into() | |
550 | } | |
1a4d82fc JJ |
551 | |
552 | /// Consumes the `BinaryHeap` and returns a vector in sorted | |
553 | /// (ascending) order. | |
554 | /// | |
555 | /// # Examples | |
556 | /// | |
54a0048b SL |
557 | /// Basic usage: |
558 | /// | |
1a4d82fc JJ |
559 | /// ``` |
560 | /// use std::collections::BinaryHeap; | |
561 | /// | |
b039eaaf | 562 | /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]); |
1a4d82fc JJ |
563 | /// heap.push(6); |
564 | /// heap.push(3); | |
565 | /// | |
566 | /// let vec = heap.into_sorted_vec(); | |
c34b1796 | 567 | /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]); |
1a4d82fc | 568 | /// ``` |
b039eaaf | 569 | #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] |
1a4d82fc JJ |
570 | pub fn into_sorted_vec(mut self) -> Vec<T> { |
571 | let mut end = self.len(); | |
572 | while end > 1 { | |
573 | end -= 1; | |
574 | self.data.swap(0, end); | |
575 | self.sift_down_range(0, end); | |
576 | } | |
577 | self.into_vec() | |
578 | } | |
579 | ||
580 | // The implementations of sift_up and sift_down use unsafe blocks in | |
581 | // order to move an element out of the vector (leaving behind a | |
d9579d0f AL |
582 | // hole), shift along the others and move the removed element back into the |
583 | // vector at the final location of the hole. | |
584 | // The `Hole` type is used to represent this, and make sure | |
585 | // the hole is filled back at the end of its scope, even on panic. | |
586 | // Using a hole reduces the constant factor compared to using swaps, | |
587 | // which involves twice as many moves. | |
588 | fn sift_up(&mut self, start: usize, pos: usize) { | |
1a4d82fc | 589 | unsafe { |
d9579d0f AL |
590 | // Take out the value at `pos` and create a hole. |
591 | let mut hole = Hole::new(&mut self.data, pos); | |
1a4d82fc | 592 | |
d9579d0f AL |
593 | while hole.pos() > start { |
594 | let parent = (hole.pos() - 1) / 2; | |
92a42be0 SL |
595 | if hole.element() <= hole.get(parent) { |
596 | break; | |
597 | } | |
d9579d0f | 598 | hole.move_to(parent); |
1a4d82fc | 599 | } |
1a4d82fc JJ |
600 | } |
601 | } | |
602 | ||
92a42be0 SL |
603 | /// Take an element at `pos` and move it down the heap, |
604 | /// while its children are larger. | |
605 | fn sift_down_range(&mut self, pos: usize, end: usize) { | |
1a4d82fc | 606 | unsafe { |
d9579d0f | 607 | let mut hole = Hole::new(&mut self.data, pos); |
1a4d82fc JJ |
608 | let mut child = 2 * pos + 1; |
609 | while child < end { | |
610 | let right = child + 1; | |
92a42be0 | 611 | // compare with the greater of the two children |
d9579d0f | 612 | if right < end && !(hole.get(child) > hole.get(right)) { |
1a4d82fc JJ |
613 | child = right; |
614 | } | |
92a42be0 SL |
615 | // if we are already in order, stop. |
616 | if hole.element() >= hole.get(child) { | |
617 | break; | |
618 | } | |
d9579d0f AL |
619 | hole.move_to(child); |
620 | child = 2 * hole.pos() + 1; | |
1a4d82fc | 621 | } |
1a4d82fc JJ |
622 | } |
623 | } | |
624 | ||
85aaf69f | 625 | fn sift_down(&mut self, pos: usize) { |
1a4d82fc JJ |
626 | let len = self.len(); |
627 | self.sift_down_range(pos, len); | |
628 | } | |
629 | ||
9cc50fc6 SL |
630 | /// Take an element at `pos` and move it all the way down the heap, |
631 | /// then sift it up to its position. | |
632 | /// | |
633 | /// Note: This is faster when the element is known to be large / should | |
634 | /// be closer to the bottom. | |
635 | fn sift_down_to_bottom(&mut self, mut pos: usize) { | |
636 | let end = self.len(); | |
637 | let start = pos; | |
638 | unsafe { | |
639 | let mut hole = Hole::new(&mut self.data, pos); | |
640 | let mut child = 2 * pos + 1; | |
641 | while child < end { | |
642 | let right = child + 1; | |
643 | // compare with the greater of the two children | |
644 | if right < end && !(hole.get(child) > hole.get(right)) { | |
645 | child = right; | |
646 | } | |
647 | hole.move_to(child); | |
648 | child = 2 * hole.pos() + 1; | |
649 | } | |
650 | pos = hole.pos; | |
651 | } | |
652 | self.sift_up(start, pos); | |
653 | } | |
654 | ||
1a4d82fc | 655 | /// Returns the length of the binary heap. |
54a0048b SL |
656 | /// |
657 | /// # Examples | |
658 | /// | |
659 | /// Basic usage: | |
660 | /// | |
661 | /// ``` | |
662 | /// use std::collections::BinaryHeap; | |
663 | /// let heap = BinaryHeap::from(vec![1, 3]); | |
664 | /// | |
665 | /// assert_eq!(heap.len(), 2); | |
666 | /// ``` | |
85aaf69f | 667 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
668 | pub fn len(&self) -> usize { |
669 | self.data.len() | |
670 | } | |
1a4d82fc JJ |
671 | |
672 | /// Checks if the binary heap is empty. | |
54a0048b SL |
673 | /// |
674 | /// # Examples | |
675 | /// | |
676 | /// Basic usage: | |
677 | /// | |
678 | /// ``` | |
679 | /// use std::collections::BinaryHeap; | |
680 | /// let mut heap = BinaryHeap::new(); | |
681 | /// | |
682 | /// assert!(heap.is_empty()); | |
683 | /// | |
684 | /// heap.push(3); | |
685 | /// heap.push(5); | |
686 | /// heap.push(1); | |
687 | /// | |
688 | /// assert!(!heap.is_empty()); | |
689 | /// ``` | |
85aaf69f | 690 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
691 | pub fn is_empty(&self) -> bool { |
692 | self.len() == 0 | |
693 | } | |
1a4d82fc JJ |
694 | |
695 | /// Clears the binary heap, returning an iterator over the removed elements. | |
c34b1796 AL |
696 | /// |
697 | /// The elements are removed in arbitrary order. | |
54a0048b SL |
698 | /// |
699 | /// # Examples | |
700 | /// | |
701 | /// Basic usage: | |
702 | /// | |
703 | /// ``` | |
704 | /// use std::collections::BinaryHeap; | |
705 | /// let mut heap = BinaryHeap::from(vec![1, 3]); | |
706 | /// | |
707 | /// assert!(!heap.is_empty()); | |
708 | /// | |
709 | /// for x in heap.drain() { | |
710 | /// println!("{}", x); | |
711 | /// } | |
712 | /// | |
713 | /// assert!(heap.is_empty()); | |
714 | /// ``` | |
1a4d82fc | 715 | #[inline] |
92a42be0 | 716 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc | 717 | pub fn drain(&mut self) -> Drain<T> { |
d9579d0f | 718 | Drain { iter: self.data.drain(..) } |
1a4d82fc JJ |
719 | } |
720 | ||
721 | /// Drops all items from the binary heap. | |
54a0048b SL |
722 | /// |
723 | /// # Examples | |
724 | /// | |
725 | /// Basic usage: | |
726 | /// | |
727 | /// ``` | |
728 | /// use std::collections::BinaryHeap; | |
729 | /// let mut heap = BinaryHeap::from(vec![1, 3]); | |
730 | /// | |
731 | /// assert!(!heap.is_empty()); | |
732 | /// | |
733 | /// heap.clear(); | |
734 | /// | |
735 | /// assert!(heap.is_empty()); | |
736 | /// ``` | |
85aaf69f | 737 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
738 | pub fn clear(&mut self) { |
739 | self.drain(); | |
740 | } | |
1a4d82fc JJ |
741 | } |
742 | ||
d9579d0f AL |
743 | /// Hole represents a hole in a slice i.e. an index without valid value |
744 | /// (because it was moved from or duplicated). | |
745 | /// In drop, `Hole` will restore the slice by filling the hole | |
746 | /// position with the value that was originally removed. | |
747 | struct Hole<'a, T: 'a> { | |
748 | data: &'a mut [T], | |
749 | /// `elt` is always `Some` from new until drop. | |
750 | elt: Option<T>, | |
751 | pos: usize, | |
752 | } | |
753 | ||
754 | impl<'a, T> Hole<'a, T> { | |
755 | /// Create a new Hole at index `pos`. | |
756 | fn new(data: &'a mut [T], pos: usize) -> Self { | |
757 | unsafe { | |
758 | let elt = ptr::read(&data[pos]); | |
759 | Hole { | |
760 | data: data, | |
761 | elt: Some(elt), | |
762 | pos: pos, | |
763 | } | |
764 | } | |
765 | } | |
766 | ||
767 | #[inline(always)] | |
92a42be0 SL |
768 | fn pos(&self) -> usize { |
769 | self.pos | |
770 | } | |
d9579d0f AL |
771 | |
772 | /// Return a reference to the element removed | |
773 | #[inline(always)] | |
92a42be0 | 774 | fn element(&self) -> &T { |
d9579d0f AL |
775 | self.elt.as_ref().unwrap() |
776 | } | |
777 | ||
778 | /// Return a reference to the element at `index`. | |
779 | /// | |
780 | /// Panics if the index is out of bounds. | |
781 | /// | |
782 | /// Unsafe because index must not equal pos. | |
783 | #[inline(always)] | |
784 | unsafe fn get(&self, index: usize) -> &T { | |
785 | debug_assert!(index != self.pos); | |
786 | &self.data[index] | |
787 | } | |
788 | ||
789 | /// Move hole to new location | |
790 | /// | |
791 | /// Unsafe because index must not equal pos. | |
792 | #[inline(always)] | |
793 | unsafe fn move_to(&mut self, index: usize) { | |
794 | debug_assert!(index != self.pos); | |
795 | let index_ptr: *const _ = &self.data[index]; | |
796 | let hole_ptr = &mut self.data[self.pos]; | |
797 | ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1); | |
798 | self.pos = index; | |
799 | } | |
800 | } | |
801 | ||
802 | impl<'a, T> Drop for Hole<'a, T> { | |
803 | fn drop(&mut self) { | |
804 | // fill the hole again | |
805 | unsafe { | |
806 | let pos = self.pos; | |
807 | ptr::write(&mut self.data[pos], self.elt.take().unwrap()); | |
808 | } | |
809 | } | |
810 | } | |
811 | ||
1a4d82fc | 812 | /// `BinaryHeap` iterator. |
85aaf69f | 813 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 814 | pub struct Iter<'a, T: 'a> { |
1a4d82fc JJ |
815 | iter: slice::Iter<'a, T>, |
816 | } | |
817 | ||
818 | // FIXME(#19839) Remove in favor of `#[derive(Clone)]` | |
85aaf69f | 819 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
820 | impl<'a, T> Clone for Iter<'a, T> { |
821 | fn clone(&self) -> Iter<'a, T> { | |
822 | Iter { iter: self.iter.clone() } | |
823 | } | |
824 | } | |
825 | ||
85aaf69f | 826 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
827 | impl<'a, T> Iterator for Iter<'a, T> { |
828 | type Item = &'a T; | |
829 | ||
830 | #[inline] | |
92a42be0 SL |
831 | fn next(&mut self) -> Option<&'a T> { |
832 | self.iter.next() | |
833 | } | |
1a4d82fc JJ |
834 | |
835 | #[inline] | |
92a42be0 SL |
836 | fn size_hint(&self) -> (usize, Option<usize>) { |
837 | self.iter.size_hint() | |
838 | } | |
1a4d82fc JJ |
839 | } |
840 | ||
85aaf69f | 841 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
842 | impl<'a, T> DoubleEndedIterator for Iter<'a, T> { |
843 | #[inline] | |
92a42be0 SL |
844 | fn next_back(&mut self) -> Option<&'a T> { |
845 | self.iter.next_back() | |
846 | } | |
1a4d82fc JJ |
847 | } |
848 | ||
85aaf69f | 849 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
850 | impl<'a, T> ExactSizeIterator for Iter<'a, T> {} |
851 | ||
852 | /// An iterator that moves out of a `BinaryHeap`. | |
85aaf69f | 853 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
854 | pub struct IntoIter<T> { |
855 | iter: vec::IntoIter<T>, | |
856 | } | |
857 | ||
85aaf69f | 858 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
859 | impl<T> Iterator for IntoIter<T> { |
860 | type Item = T; | |
861 | ||
862 | #[inline] | |
92a42be0 SL |
863 | fn next(&mut self) -> Option<T> { |
864 | self.iter.next() | |
865 | } | |
1a4d82fc JJ |
866 | |
867 | #[inline] | |
92a42be0 SL |
868 | fn size_hint(&self) -> (usize, Option<usize>) { |
869 | self.iter.size_hint() | |
870 | } | |
1a4d82fc JJ |
871 | } |
872 | ||
85aaf69f | 873 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
874 | impl<T> DoubleEndedIterator for IntoIter<T> { |
875 | #[inline] | |
92a42be0 SL |
876 | fn next_back(&mut self) -> Option<T> { |
877 | self.iter.next_back() | |
878 | } | |
1a4d82fc JJ |
879 | } |
880 | ||
85aaf69f | 881 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
882 | impl<T> ExactSizeIterator for IntoIter<T> {} |
883 | ||
884 | /// An iterator that drains a `BinaryHeap`. | |
92a42be0 | 885 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
886 | pub struct Drain<'a, T: 'a> { |
887 | iter: vec::Drain<'a, T>, | |
888 | } | |
889 | ||
85aaf69f | 890 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
891 | impl<'a, T: 'a> Iterator for Drain<'a, T> { |
892 | type Item = T; | |
893 | ||
894 | #[inline] | |
92a42be0 SL |
895 | fn next(&mut self) -> Option<T> { |
896 | self.iter.next() | |
897 | } | |
1a4d82fc JJ |
898 | |
899 | #[inline] | |
92a42be0 SL |
900 | fn size_hint(&self) -> (usize, Option<usize>) { |
901 | self.iter.size_hint() | |
902 | } | |
1a4d82fc JJ |
903 | } |
904 | ||
85aaf69f | 905 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
906 | impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { |
907 | #[inline] | |
92a42be0 SL |
908 | fn next_back(&mut self) -> Option<T> { |
909 | self.iter.next_back() | |
910 | } | |
1a4d82fc JJ |
911 | } |
912 | ||
85aaf69f | 913 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
914 | impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {} |
915 | ||
92a42be0 | 916 | #[stable(feature = "rust1", since = "1.0.0")] |
b039eaaf SL |
917 | impl<T: Ord> From<Vec<T>> for BinaryHeap<T> { |
918 | fn from(vec: Vec<T>) -> BinaryHeap<T> { | |
919 | let mut heap = BinaryHeap { data: vec }; | |
920 | let mut n = heap.len() / 2; | |
921 | while n > 0 { | |
922 | n -= 1; | |
923 | heap.sift_down(n); | |
924 | } | |
925 | heap | |
926 | } | |
927 | } | |
928 | ||
92a42be0 | 929 | #[stable(feature = "rust1", since = "1.0.0")] |
b039eaaf SL |
930 | impl<T> From<BinaryHeap<T>> for Vec<T> { |
931 | fn from(heap: BinaryHeap<T>) -> Vec<T> { | |
932 | heap.data | |
933 | } | |
934 | } | |
935 | ||
85aaf69f | 936 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 937 | impl<T: Ord> FromIterator<T> for BinaryHeap<T> { |
92a42be0 | 938 | fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> { |
b039eaaf | 939 | BinaryHeap::from(iter.into_iter().collect::<Vec<_>>()) |
85aaf69f SL |
940 | } |
941 | } | |
942 | ||
943 | #[stable(feature = "rust1", since = "1.0.0")] | |
944 | impl<T: Ord> IntoIterator for BinaryHeap<T> { | |
945 | type Item = T; | |
946 | type IntoIter = IntoIter<T>; | |
947 | ||
9346a6ac AL |
948 | /// Creates a consuming iterator, that is, one that moves each value out of |
949 | /// the binary heap in arbitrary order. The binary heap cannot be used | |
950 | /// after calling this. | |
951 | /// | |
952 | /// # Examples | |
953 | /// | |
54a0048b SL |
954 | /// Basic usage: |
955 | /// | |
9346a6ac | 956 | /// ``` |
9346a6ac | 957 | /// use std::collections::BinaryHeap; |
b039eaaf | 958 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]); |
9346a6ac AL |
959 | /// |
960 | /// // Print 1, 2, 3, 4 in arbitrary order | |
961 | /// for x in heap.into_iter() { | |
962 | /// // x has type i32, not &i32 | |
963 | /// println!("{}", x); | |
964 | /// } | |
965 | /// ``` | |
85aaf69f | 966 | fn into_iter(self) -> IntoIter<T> { |
9346a6ac | 967 | IntoIter { iter: self.data.into_iter() } |
85aaf69f SL |
968 | } |
969 | } | |
970 | ||
971 | #[stable(feature = "rust1", since = "1.0.0")] | |
972 | impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord { | |
973 | type Item = &'a T; | |
974 | type IntoIter = Iter<'a, T>; | |
975 | ||
976 | fn into_iter(self) -> Iter<'a, T> { | |
977 | self.iter() | |
1a4d82fc JJ |
978 | } |
979 | } | |
980 | ||
85aaf69f | 981 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 982 | impl<T: Ord> Extend<T> for BinaryHeap<T> { |
54a0048b SL |
983 | fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { |
984 | let iterator = iter.into_iter(); | |
985 | let (lower, _) = iterator.size_hint(); | |
1a4d82fc JJ |
986 | |
987 | self.reserve(lower); | |
988 | ||
54a0048b | 989 | for elem in iterator { |
1a4d82fc JJ |
990 | self.push(elem); |
991 | } | |
992 | } | |
993 | } | |
62682a34 SL |
994 | |
995 | #[stable(feature = "extend_ref", since = "1.2.0")] | |
996 | impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> { | |
92a42be0 | 997 | fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { |
62682a34 SL |
998 | self.extend(iter.into_iter().cloned()); |
999 | } | |
1000 | } |