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

This commit is contained in:
nuomi1
2023-03-30 01:59:14 +08:00
committed by GitHub
parent 264adf250a
commit 944c34982c
2 changed files with 45 additions and 0 deletions

View File

@@ -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)")
}
}