Add Zig code blocks.

This commit is contained in:
Yudong Jin
2023-02-01 22:03:04 +08:00
parent 6cd6d5589e
commit 7ce7386bab
25 changed files with 599 additions and 0 deletions

View File

@@ -232,6 +232,12 @@ comments: true
}
```
=== "Zig"
```zig title="bubble_sort.zig"
```
## 11.2.2. 算法特性
**时间复杂度 $O(n^2)$** :各轮「冒泡」遍历的数组长度为 $n - 1$ , $n - 2$ , $\cdots$ , $2$ , $1$ 次,求和为 $\frac{(n - 1) n}{2}$ ,因此使用 $O(n^2)$ 时间。
@@ -458,3 +464,9 @@ comments: true
}
}
```
=== "Zig"
```zig title="bubble_sort.zig"
```

View File

@@ -194,6 +194,12 @@ comments: true
}
```
=== "Zig"
```zig title="insertion_sort.zig"
```
## 11.3.2. 算法特性
**时间复杂度 $O(n^2)$** :最差情况下,各轮插入操作循环 $n - 1$ , $n-2$ , $\cdots$ , $2$ , $1$ 次,求和为 $\frac{(n - 1) n}{2}$ ,使用 $O(n^2)$ 时间。

View File

@@ -442,6 +442,12 @@ comments: true
}
```
=== "Zig"
```zig title="merge_sort.zig"
```
下面重点解释一下合并方法 `merge()` 的流程:
1. 初始化一个辅助数组 `tmp` 暂存待合并区间 `[left, right]` 内的元素,后续通过覆盖原数组 `nums` 的元素来实现合并;

View File

@@ -259,6 +259,12 @@ comments: true
}
```
=== "Zig"
```zig title="quick_sort.zig"
```
!!! note "快速排序的分治思想"
哨兵划分的实质是将 **一个长数组的排序问题** 简化为 **两个短数组的排序问题**。
@@ -412,6 +418,12 @@ comments: true
}
```
=== "Zig"
```zig title="quick_sort.zig"
```
## 11.4.2. 算法特性
**平均时间复杂度 $O(n \log n)$** :平均情况下,哨兵划分的递归层数为 $\log n$ ,每层中的总循环数为 $n$ ,总体使用 $O(n \log n)$ 时间。
@@ -652,6 +664,12 @@ comments: true
}
```
=== "Zig"
```zig title="quick_sort.zig"
```
## 11.4.5. 尾递归优化
**普通快速排序在某些输入下的空间效率变差**。仍然以完全倒序的输入数组为例,由于每轮哨兵划分后右子数组长度为 0 ,那么将形成一个高度为 $n - 1$ 的递归树,此时使用的栈帧空间大小劣化至 $O(n)$ 。
@@ -835,3 +853,9 @@ comments: true
}
}
```
=== "Zig"
```zig title="quick_sort.zig"
```