Skip to content

Commit 53fb071

Browse files
authored
Update algorithm9.rs
1 parent 62974f6 commit 53fb071

File tree

1 file changed

+54
-9
lines changed

1 file changed

+54
-9
lines changed

exercises/algorithm/algorithm9.rs

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
/*
2-
heap
3-
This question requires you to implement a binary heap function
2+
heap
3+
This question requires you to implement a binary heap function
44
*/
5-
// I AM NOT DONE
65

76
use std::cmp::Ord;
87
use std::default::Default;
@@ -37,7 +36,17 @@ where
3736
}
3837

3938
pub fn add(&mut self, value: T) {
40-
//TODO
39+
self.count += 1;
40+
if self.count >= self.items.len() {
41+
self.items.push(value);
42+
} else {
43+
self.items[self.count] = value;
44+
}
45+
let mut idx = self.count;
46+
while idx / 2 > 0 && (self.comparator)(&self.items[idx], &self.items[idx / 2]) {
47+
self.items.swap(idx, idx / 2);
48+
idx = idx / 2;
49+
}
4150
}
4251

4352
fn parent_idx(&self, idx: usize) -> usize {
@@ -57,8 +66,18 @@ where
5766
}
5867

5968
fn smallest_child_idx(&self, idx: usize) -> usize {
60-
//TODO
61-
0
69+
let left = self.left_child_idx(idx);
70+
let right = self.right_child_idx(idx);
71+
72+
if right > self.count {
73+
left
74+
} else {
75+
if (self.comparator)(&self.items[left], &self.items[right]) {
76+
left
77+
} else {
78+
right
79+
}
80+
}
6281
}
6382
}
6483

@@ -84,8 +103,34 @@ where
84103
type Item = T;
85104

86105
fn next(&mut self) -> Option<T> {
87-
//TODO
88-
None
106+
if self.is_empty() {
107+
return None;
108+
}
109+
110+
self.items.swap(1, self.count);
111+
self.count -= 1;
112+
113+
let root = self.items.pop();
114+
115+
let mut i = 1;
116+
let mut maxPos = i;
117+
loop {
118+
if i * 2 < self.count && (self.comparator)(&self.items[i * 2], &self.items[i]) {
119+
maxPos = i * 2;
120+
}
121+
if i * 2 + 1 < self.count
122+
&& (self.comparator)(&self.items[i * 2 + 1], &self.items[self.count])
123+
{
124+
maxPos = i * 2 + 1;
125+
}
126+
if maxPos == i {
127+
break;
128+
}
129+
self.items.swap(i, maxPos);
130+
i = maxPos;
131+
}
132+
133+
root
89134
}
90135
}
91136

@@ -151,4 +196,4 @@ mod tests {
151196
heap.add(1);
152197
assert_eq!(heap.next(), Some(2));
153198
}
154-
}
199+
}

0 commit comments

Comments
 (0)