Forráskód Böngészése

Replaced vector with minheap

Should be more efficient.
AvariceLHubris 1 éve
szülő
commit
86862cf49c
1 módosított fájl, 10 hozzáadás és 13 törlés
  1. 10 13
      src/hufftree/base.rs

+ 10 - 13
src/hufftree/base.rs

@@ -1,5 +1,6 @@
 use bit_vec::BitVec;
-use std::collections::HashMap;
+use core::cmp::Reverse;
+use std::collections::{BinaryHeap, HashMap};
 
 use crate::node::Node;
 
@@ -11,35 +12,31 @@ pub struct Hufftree {
 
 impl Hufftree {
     pub fn new(chars_and_freq: HashMap<char, i32>) -> Hufftree {
-        let mut nodes: Vec<Node> = Vec::new();
+        // Min heap for better performance.
+        let mut nodes: BinaryHeap<Reverse<Node>> = BinaryHeap::new();
         let mut characters: Vec<char> = Vec::new();
 
         for (c, f) in chars_and_freq {
-            nodes.push(Node::new_with_character(c, f));
+            nodes.push(Reverse(Node::new_with_character(c, f)));
             characters.push(c);
         }
 
-        nodes.sort();
-        nodes.reverse();
 
         while nodes.len() > 1 {
-            let n1 = nodes.pop().expect("There was no node left in the vector.");
-            let n2 = nodes.pop().expect("There was no node left in the vector.");
+            let Reverse(n1) = nodes.pop().expect("There was no node left in the vector.");
+            let Reverse(n2) = nodes.pop().expect("There was no node left in the vector.");
 
             let mut new_node = Node::new();
 
             new_node.join_left(Box::new(n1));
             new_node.join_right(Box::new(n2));
 
-            nodes.push(new_node);
-
-            // TODO: Optimize this later.
-            nodes.sort();
-            nodes.reverse();
+            nodes.push(Reverse(new_node));
         }
 
+        let Reverse(root) = nodes.pop().expect("There was no node in the vector.");
         Hufftree {
-            root: nodes.pop().expect("There was no node in the vector."),
+            root,
             characters,
         }
     }