基数排序是首先求出最大数的个数,然后从低位到高位分别放到对应0-9的桶中,按照先进先出的规则
找到最大数是321,个数是3。
按照百分位进行桶排序
此时已经排序完成
class Solution {
func baseSort(_ numbers:[Int]) -> [Int] {
guard numbers.count > 1 else {
return numbers
}
var maxValue:Int = 0
for i in 0 ..< numbers.count {
maxValue = max(numbers[i], maxValue)
}
let maxLenght = "\(maxValue)".count
var list:[Int] = numbers
for i in 0 ..< maxLenght {
list = bucketSort(list, i)
}
return list
}
func bucketSort(_ numbers:[Int], _ base:Int) -> [Int] {
var buckets:[[Int]] = Array(repeating: [], count: 9)
for i in 0 ..< numbers.count {
let n = "\(numbers[i])"
if n.count > base, let baseValue = Int(String(n[n.index(n.endIndex, offsetBy: (-1 - base))])) {
var list = buckets[baseValue]
list.append(numbers[i])
buckets[baseValue] = list
} else {
var list = buckets[0]
list.append(numbers[i])
buckets[0] = list
}
}
var list:[Int] = []
for i in 0 ..< buckets.count {
list += buckets[i]
}
return list
}
}