This commit is contained in:
krahets 2023-03-23 03:00:34 +08:00
parent 89b4c200a5
commit 6f577dfe0b
2 changed files with 51 additions and 4 deletions

View file

@ -1516,7 +1516,7 @@ $$
func bubbleSort(nums: inout [Int]) -> Int { func bubbleSort(nums: inout [Int]) -> Int {
var count = 0 // 计数器 var count = 0 // 计数器
// 外循环:待排序元素数量为 n-1, n-2, ..., 1 // 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in sequence(first: nums.count - 1, next: { $0 > 0 + 1 ? $0 - 1 : nil }) { for i in stride(from: nums.count - 1, to: 0, by: -1) {
// 内循环:冒泡操作 // 内循环:冒泡操作
for j in 0 ..< i { for j in 0 ..< i {
if nums[j] > nums[j + 1] { if nums[j] > nums[j + 1] {
@ -2221,7 +2221,7 @@ $$
return 1 return 1
} }
var count = linearLogRecur(n: n / 2) + linearLogRecur(n: n / 2) var count = linearLogRecur(n: n / 2) + linearLogRecur(n: n / 2)
for _ in sequence(first: 0, next: { $0 < n - 1 ? $0 + 1 : nil }) { for _ in stride(from: 0, to: n, by: 1) {
count += 1 count += 1
} }
return count return count

View file

@ -158,7 +158,26 @@ comments: true
=== "Swift" === "Swift"
```swift title="counting_sort.swift" ```swift title="counting_sort.swift"
[class]{}-[func]{countingSortNaive} /* 计数排序 */
// 简单实现,无法用于排序对象
func countingSortNaive(nums: inout [Int]) {
// 1. 统计数组最大元素 m
let m = nums.max()!
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
var counter = Array(repeating: 0, count: m + 1)
for num in nums {
counter[num] += 1
}
// 3. 遍历 counter ,将各元素填入原数组 nums
var i = 0
for num in stride(from: 0, to: m + 1, by: 1) {
for _ in stride(from: 0, to: counter[num], by: 1) {
nums[i] = num
i += 1
}
}
}
``` ```
=== "Zig" === "Zig"
@ -381,7 +400,35 @@ $$
=== "Swift" === "Swift"
```swift title="counting_sort.swift" ```swift title="counting_sort.swift"
[class]{}-[func]{countingSort} /* 计数排序 */
// 完整实现,可排序对象,并且是稳定排序
func countingSort(nums: inout [Int]) {
// 1. 统计数组最大元素 m
let m = nums.max()!
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
var counter = Array(repeating: 0, count: m + 1)
for num in nums {
counter[num] += 1
}
// 3. 求 counter 的前缀和,将“出现次数”转换为“尾索引”
// 即 counter[num]-1 是 num 在 res 中最后一次出现的索引
for i in stride(from: 0, to: m, by: 1) {
counter[i + 1] += counter[i]
}
// 4. 倒序遍历 nums ,将各元素填入结果数组 res
// 初始化数组 res 用于记录结果
var res = Array(repeating: 0, count: nums.count)
for i in stride(from: nums.count - 1, through: 0, by: -1) {
let num = nums[i]
res[counter[num] - 1] = num // 将 num 放置到对应索引处
counter[num] -= 1 // 令前缀和自减 1 ,得到下次放置 num 的索引
}
// 使用结果数组 res 覆盖原数组 nums
for i in stride(from: 0, to: nums.count, by: 1) {
nums[i] = res[i]
}
}
``` ```
=== "Zig" === "Zig"