feat: add Swift codes for bucket_sort article (#444)

pull/446/head
nuomi1 2 years ago committed by GitHub
parent 264adf250a
commit 944c34982c
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: "insertion_sort", targets: ["insertion_sort"]),
.executable(name: "quick_sort", targets: ["quick_sort"]), .executable(name: "quick_sort", targets: ["quick_sort"]),
.executable(name: "merge_sort", targets: ["merge_sort"]), .executable(name: "merge_sort", targets: ["merge_sort"]),
.executable(name: "bucket_sort", targets: ["bucket_sort"]),
.executable(name: "counting_sort", targets: ["counting_sort"]), .executable(name: "counting_sort", targets: ["counting_sort"]),
.executable(name: "radix_sort", targets: ["radix_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: "insertion_sort", path: "chapter_sorting", sources: ["insertion_sort.swift"]),
.executableTarget(name: "quick_sort", path: "chapter_sorting", sources: ["quick_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: "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: "counting_sort", path: "chapter_sorting", sources: ["counting_sort.swift"]),
.executableTarget(name: "radix_sort", path: "chapter_sorting", sources: ["radix_sort.swift"]), .executableTarget(name: "radix_sort", path: "chapter_sorting", sources: ["radix_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)")
}
}
Loading…
Cancel
Save