-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
103 lines (95 loc) · 2.2 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#[derive(Debug)]
pub struct MinHeap {
vals: Vec<i32>,
}
impl Default for MinHeap {
fn default() -> MinHeap {
MinHeap { vals: vec![0] }
}
}
impl MinHeap {
pub fn new() -> MinHeap {
MinHeap::default()
}
/// Returns true if the heap contains no elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::minheap::MinHeap;
///
/// let mut a = MinHeap::new();
/// assert!(a.is_empty());
/// a.insert(1);
/// assert!(!a.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.vals.len() - 1
}
/// Inserts a value into the heap.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use yaar::minheap::MinHeap;
///
/// let mut heap = MinHeap::new();
/// heap.insert(37);
/// assert_eq!(heap.is_empty(), false);
/// ```
pub fn insert(&mut self, value: i32) {
let mut i = self.vals.len();
self.vals.push(value);
while i > 1 && self.vals[i / 2].gt(&self.vals[i]) {
self.vals.swap(i, i / 2);
i /= 2;
}
}
pub fn pop(&mut self) -> Option<i32> {
if !self.is_empty() {
let mut i = 1;
let len = self.len();
self.vals.swap(1, len);
let min = self.vals.pop();
let len = self.len();
while i * 2 <= len {
let ii = i * 2;
let j = if ii < len && self.vals[ii].gt(&self.vals[ii + 1]) {
ii + 1
} else {
ii
};
if !self.vals[i].gt(&self.vals[j]) {
break;
}
self.vals.swap(i, j);
i = j;
}
min
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_sequence() {
let mut heap = MinHeap::new();
for i in (0..256).rev() {
heap.insert(i);
}
for i in 0..256 {
assert_eq!(Some(i), heap.pop());
}
assert_eq!(None, heap.pop());
}
}