From 944c34982c58776a763cc152aaa2f1cef8551f45 Mon Sep 17 00:00:00 2001 From: nuomi1 Date: Thu, 30 Mar 2023 01:59:14 +0800 Subject: [PATCH] feat: add Swift codes for bucket_sort article (#444) --- codes/swift/Package.swift | 2 + codes/swift/chapter_sorting/bucket_sort.swift | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 codes/swift/chapter_sorting/bucket_sort.swift diff --git a/codes/swift/Package.swift b/codes/swift/Package.swift index 21192e581..7e7993cac 100644 --- a/codes/swift/Package.swift +++ b/codes/swift/Package.swift @@ -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: "bucket_sort", targets: ["bucket_sort"]), .executable(name: "counting_sort", targets: ["counting_sort"]), .executable(name: "radix_sort", targets: ["radix_sort"]), ], @@ -102,6 +103,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: "bucket_sort", path: "chapter_sorting", sources: ["bucket_sort.swift"]), .executableTarget(name: "counting_sort", path: "chapter_sorting", sources: ["counting_sort.swift"]), .executableTarget(name: "radix_sort", path: "chapter_sorting", sources: ["radix_sort.swift"]), ] diff --git a/codes/swift/chapter_sorting/bucket_sort.swift b/codes/swift/chapter_sorting/bucket_sort.swift new file mode 100644 index 000000000..f090cbdfe --- /dev/null +++ b/codes/swift/chapter_sorting/bucket_sort.swift @@ -0,0 +1,43 @@ +/** + * File: bucket_sort.swift + * Created Time: 2023-03-27 + * Author: nuomi1 (nuomi1@qq.com) + */ + +/* 桶排序 */ +func bucketSort(nums: inout [Double]) { + // 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素 + let k = nums.count / 2 + var buckets = (0 ..< k).map { _ in [Double]() } + // 1. 将数组元素分配到各个桶中 + for num in nums { + // 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1] + let i = Int(num) * k + // 将 num 添加进桶 i + buckets[i].append(num) + } + // 2. 对各个桶执行排序 + for i in buckets.indices { + // 使用内置排序函数,也可以替换成其它排序算法 + buckets[i].sort() + } + // 3. 遍历桶合并结果 + var i = nums.startIndex + for bucket in buckets { + for num in bucket { + nums[i] = num + nums.formIndex(after: &i) + } + } +} + +@main +enum BucketSort { + /* Driver Code */ + static func main() { + // 设输入数据为浮点数,范围为 [0, 1) + var nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37] + bucketSort(nums: &nums) + print("桶排序完成后 nums = \(nums)") + } +}