Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
System Administrator authored and System Administrator committed Apr 22, 2024
1 parent fe1ca70 commit 9764f9f
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"server": "hexo server"
},
"hexo": {
"version": "7.0.0"
"version": "4.2.1"
},
"dependencies": {
"hexo": "^4.2.1",
Expand All @@ -25,4 +25,4 @@
"hexo-renderer-stylus": "^1.1.0",
"hexo-server": "^1.0.0"
}
}
}
5 changes: 5 additions & 0 deletions source/_posts/algorithm-blogs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: algorithm-blogs
date: 2024-04-23 00:19:38
tags:
---
37 changes: 37 additions & 0 deletions source/_posts/algorithm-rusts-learning.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
title: algorithm-rusts-learning
date: 2024-04-23 00:19:47
tags:
---
提供的 Rust 代码实现了一个通用的二叉堆,支持最小堆和最大堆的功能。下面是这个实现的核心组成部分的详细解释:

1. **结构定义 (`Heap<T>`)**
- `T: Default`:这个约束确保堆中的元素可以被初始化为默认值。这对于确保堆的向量(`items`)可以在索引0处有一个占位符,简化索引计算非常有用。
- `count`:跟踪堆中的元素数量。
- `items`:一个向量,存储堆元素。堆使用基于1的索引以简化父子计算,索引0保持为虚拟。
- `comparator`:一个函数指针,用于确定元素的排序,允许灵活定义最小堆或最大堆。

2. **构造函数 (`new(comparator)`)**
- 使用提供的比较函数初始化一个空堆,用于元素排序。

3. **堆操作**
- **添加元素 (`add`)**:在堆的末尾插入一个新元素,然后将其向上移动以维护堆属性。这是通过比较添加的元素与其父元素并根据比较函数进行必要的交换来完成的。
- **移除根元素 (`next` in `Iterator` implementation)**:移除根元素(根据堆的类型是最小或最大),将其替换为堆中的最后一个元素,然后将此元素向下移动以维护堆属性。在此过程中,堆的大小减少一个。

4. **辅助函数**
- `parent_idx`, `children_present`, `left_child_idx`, `right_child_idx`, `smallest_child_idx`:这些辅助函数用于计算父和子的索引或检查子节点的存在,这对于在添加和删除操作期间导航堆至关重要。

5. **类型特定的堆构造器 (`MinHeap``MaxHeap`)**
- 这些是方便的包装器,提供了使用标准比较函数(对于最小堆是 `a < b`,对于最大堆是 `a > b`)轻松实例化 `Heap<T>` 的方法。

6. **测试 (`tests` module)**
- 包含测试来验证堆的功能,包括最小堆和最大堆行为的测试。

### 关键特点:
- **通用性和可重用性**:堆可以处理实现了 `Default` 的任何类型 `T`,并可以使用在实例化时传递的任何比较函数,使其可以适应不同的排序需求。
- **效率**:插入和删除操作的时间复杂度为元素数量的对数,这是二叉堆的特点。
- **迭代器集成**:通过实现带有 `next` 方法的 `Iterator` 特质,允许堆在标凈 Rust 习惯用法中使用,如循环和其他基于迭代器的操作。

### 增强建议:
- **错误处理**:考虑可能失败的场景,如尝试从空堆中移除元素,并优雅地处理

0 comments on commit 9764f9f

Please sign in to comment.