尝试在Swift中实现基数版本的MSD版本
func sort(_ array: [Int]) -> [Int]{
var arr = array
let base = 10
var digitPosition = 10
while (digitPosition>0) {
var buckets = [[Int]](repeating: [], count: base)
for number in arr {
let remainder = number / digitPosition
let numberDigit = remainder % base // base is 10
buckets[numberDigit].append(number)
}
digitPosition /= base
arr = buckets.flatMap {$0}
}
return arr
}
运行排序的输入是:
sort([112,2,3,104,15])
我的存储桶的输出如下:
[[112, 2, 3, 104, 15], [], [], [], [], [], [], [], [], []]
[[2, 3, 15], [112, 104], [], [], [], [], [], [], [], []]
[[2, 3, 104], [15, 112], [], [], [], [], [], [], [], []]
[[], [], [2, 112], [3], [104], [15], [], [], [], []]
这些是不正确的。
1。如何在Swift中将前0附加到整数
2。如何从后续执行中删除单个存储桶整数?
答案 0 :(得分:0)
如果您要显示的是前导零的整数:
let value = 3
print(String(format: "%03d", value))
将显示“ 003”
不确定“单桶整数”是什么意思