Add Swift language blocks to the docs.

This commit is contained in:
Yudong Jin
2023-01-08 19:41:05 +08:00
parent 3ba37dba3a
commit 73e3452838
22 changed files with 414 additions and 70 deletions

View File

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

View File

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

View File

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

View File

@ -223,6 +223,12 @@ comments: true
```
=== "Swift"
```swift title="quick_sort.swift"
```
!!! note "快速排序的分治思想"
哨兵划分的实质是将 **一个长数组的排序问题** 简化为 **两个短数组的排序问题**。
@ -359,6 +365,12 @@ comments: true
```
=== "Swift"
```swift title="quick_sort.swift"
```
## 算法特性
**平均时间复杂度 $O(n \log n)$ ** 平均情况下,哨兵划分的递归层数为 $\log n$ ,每层中的总循环数为 $n$ ,总体使用 $O(n \log n)$ 时间。
@ -574,6 +586,12 @@ comments: true
}
```
=== "Swift"
```swift title="quick_sort.swift"
```
## 尾递归优化
**普通快速排序在某些输入下的空间效率变差**。仍然以完全倒序的输入数组为例,由于每轮哨兵划分后右子数组长度为 0 ,那么将形成一个高度为 $n - 1$ 的递归树,此时使用的栈帧空间大小劣化至 $O(n)$ 。
@ -652,10 +670,10 @@ comments: true
// 对两个子数组中较短的那个执行快排
if pivot-left < right-pivot {
quickSort(nums, left, pivot-1) // 递归排序左子数组
left = pivot + 1 // 剩余待排序区间为 [pivot + 1, right]
left = pivot + 1 // 剩余待排序区间为 [pivot + 1, right]
} else {
quickSort(nums, pivot+1, right) // 递归排序右子数组
right = pivot - 1 // 剩余待排序区间为 [left, pivot - 1]
right = pivot - 1 // 剩余待排序区间为 [left, pivot - 1]
}
}
}
@ -734,3 +752,9 @@ comments: true
}
}
```
=== "Swift"
```swift title="quick_sort.swift"
```