feat: add Swift codes for counting_sort article (#438)

pull/439/head
nuomi1 2 years ago committed by GitHub
parent 65e47b0748
commit 5ba85ea69d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -50,6 +50,7 @@ let package = Package(
.executable(name: "insertion_sort", targets: ["insertion_sort"]),
.executable(name: "quick_sort", targets: ["quick_sort"]),
.executable(name: "merge_sort", targets: ["merge_sort"]),
.executable(name: "counting_sort", targets: ["counting_sort"]),
.executable(name: "radix_sort", targets: ["radix_sort"]),
],
targets: [
@ -101,6 +102,7 @@ let package = Package(
.executableTarget(name: "insertion_sort", path: "chapter_sorting", sources: ["insertion_sort.swift"]),
.executableTarget(name: "quick_sort", path: "chapter_sorting", sources: ["quick_sort.swift"]),
.executableTarget(name: "merge_sort", path: "chapter_sorting", sources: ["merge_sort.swift"]),
.executableTarget(name: "counting_sort", path: "chapter_sorting", sources: ["counting_sort.swift"]),
.executableTarget(name: "radix_sort", path: "chapter_sorting", sources: ["radix_sort.swift"]),
]
)

@ -0,0 +1,70 @@
/**
* File: counting_sort.swift
* Created Time: 2023-03-22
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
//
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
}
}
}
/* */
//
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]
}
}
@main
enum CountingSort {
/* Driver Code */
static func main() {
var nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]
countingSortNaive(nums: &nums)
print("计数排序(无法排序对象)完成后 nums = \(nums)")
var nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]
countingSort(nums: &nums1)
print("计数排序完成后 nums1 = \(nums1)")
}
}
Loading…
Cancel
Save