Start to implement heap

This commit is contained in:
2020-12-09 20:33:26 -05:00
parent 35b52154ca
commit 7011d04132
4 changed files with 10065 additions and 2 deletions

54
src/heap.rs Normal file
View File

@@ -0,0 +1,54 @@
#[derive(Debug)]
struct MinHeap<T> {
nodes: Vec<T>,
size: usize,
}
fn parent_index(i: usize) -> usize {
(i + 1) / 2 - 1
}
fn child_index(i: usize) -> (usize, usize) {
((i + 1) * 2 - 1, (i + 1) * 2 + 1 - 1)
}
impl<T: std::cmp::PartialOrd> MinHeap<T> {
fn new() -> Self {
Self {
nodes: Vec::with_capacity(128),
size: 0,
}
}
fn insert(&mut self, e: T) -> () {
// append at the end
self.nodes.push(e);
self.size += 1;
let last_index = self.size - 1;
let mut swap_index = self.size - 1;
while swap_index != 0 && self.nodes[last_index] < self.nodes[parent_index(swap_index)] {
swap_index = parent_index(swap_index);
}
self.nodes.swap(last_index, swap_index);
}
fn extract_min(&mut self) -> T {
if self.size == 0 {
panic!("Cannot extract key from empty heap");
}
self.nodes.swap(0, self.size - 1);
let child_indices = child_index(0);
println!("{:?}", child_indices);
self.nodes.pop().unwrap()
}
}
pub fn heap(v: &Vec<u32>) -> () {
let mut mh: MinHeap<u32> = MinHeap::new();
for i in 0..5 {
mh.insert(v[i]);
println!("{:?}", mh);
}
mh.extract_min();
}

View File

@@ -1,4 +1,5 @@
mod dijkstra;
mod heap;
mod merge_sort;
mod min_cut;
mod quick_sort;
@@ -8,6 +9,7 @@ mod util;
use std::cmp::min;
use crate::dijkstra::dijkstra;
use crate::heap::heap;
use crate::merge_sort::merge_sort_inversions;
use crate::min_cut::min_cut;
use crate::quick_sort::quick_sort;
@@ -66,10 +68,17 @@ fn c2a2() {
// [2599, 2610, 2947, 2052, 2367, 2399, 2029, 2442, 2505, 3068]
}
#[allow(dead_code)]
fn c2a3() {
let vec = util::read_to_vector("data/c2a3.txt").unwrap();
heap(&vec);
}
fn main() {
// c1a2();
// c1a3();
// c1a4();
// c2a1();
c2a2();
// c2a2();
c2a3();
}

View File

@@ -23,7 +23,7 @@ pub struct DirectedWeightedGraph {
pub distance: Vec<usize>,
}
pub fn read_to_vector(path: &str) -> Result<Vec<i64>, io::Error> {
pub fn read_to_vector(path: &str) -> Result<Vec<u32>, io::Error> {
let file = File::open(path)?;
let br = BufReader::new(file);
let mut v = Vec::new();