Add build script for Swift.

This commit is contained in:
krahets
2023-02-08 20:30:05 +08:00
parent 05f0054005
commit 38751cc5f5
25 changed files with 128 additions and 1223 deletions

View File

@@ -350,27 +350,11 @@ comments: true
=== "Swift"
```swift title="my_heap.swift"
var maxHeap: [Int]
[class]{MaxHeap}-[func]{left}
/* 构造函数,建立空堆 */
init() {
maxHeap = []
}
[class]{MaxHeap}-[func]{right}
/* 获取左子结点索引 */
func left(i: Int) -> Int {
2 * i + 1
}
/* 获取右子结点索引 */
func right(i: Int) -> Int {
2 * i + 2
}
/* 获取父结点索引 */
func parent(i: Int) -> Int {
(i - 1) / 2 // 向下整除
}
[class]{MaxHeap}-[func]{parent}
```
=== "Zig"
@@ -437,10 +421,7 @@ comments: true
=== "Swift"
```swift title="my_heap.swift"
/* 访问堆顶元素 */
func peek() -> Int {
maxHeap[0]
}
[class]{MaxHeap}-[func]{peek}
```
=== "Zig"
@@ -556,30 +537,9 @@ comments: true
=== "Swift"
```swift title="my_heap.swift"
/* 元素入堆 */
func push(val: Int) {
// 添加结点
maxHeap.append(val)
// 从底至顶堆化
siftUp(i: size() - 1)
}
[class]{MaxHeap}-[func]{push}
/* 从结点 i 开始,从底至顶堆化 */
func siftUp(i: Int) {
var i = i
while true {
// 获取结点 i 的父结点
let p = parent(i: i)
// 当“越过根结点”或“结点无需修复”时,结束堆化
if p < 0 || maxHeap[i] <= maxHeap[p] {
break
}
// 交换两结点
swap(i: i, j: p)
// 循环向上堆化
i = p
}
}
[class]{MaxHeap}-[func]{siftUp}
```
=== "Zig"
@@ -728,46 +688,9 @@ comments: true
=== "Swift"
```swift title="my_heap.swift"
/* 元素出堆 */
func poll() -> Int {
// 判空处理
if isEmpty() {
fatalError("堆为空")
}
// 交换根结点与最右叶结点(即交换首元素与尾元素)
swap(i: 0, j: size() - 1)
// 删除结点
let val = maxHeap.remove(at: size() - 1)
// 从顶至底堆化
siftDown(i: 0)
// 返回堆顶元素
return val
}
[class]{MaxHeap}-[func]{poll}
/* 从结点 i 开始,从顶至底堆化 */
func siftDown(i: Int) {
var i = i
while true {
// 判断结点 i, l, r 中值最大的结点,记为 ma
let l = left(i: i)
let r = right(i: i)
var ma = i
if l < size(), maxHeap[l] > maxHeap[ma] {
ma = l
}
if r < size(), maxHeap[r] > maxHeap[ma] {
ma = r
}
// 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
if ma == i {
break
}
// 交换两结点
swap(i: i, j: ma)
// 循环向下堆化
i = ma
}
}
[class]{MaxHeap}-[func]{siftDown}
```
=== "Zig"
@@ -842,15 +765,7 @@ comments: true
=== "Swift"
```swift title="my_heap.swift"
/* 构造函数,根据输入列表建堆 */
init(nums: [Int]) {
// 将列表元素原封不动添加进堆
maxHeap = nums
// 堆化除叶结点以外的其他所有结点
for i in stride(from: parent(i: size() - 1), through: 0, by: -1) {
siftDown(i: i)
}
}
[class]{MaxHeap}-[func]{init}
```
=== "Zig"