桶排序(Bucket sort)原理是将数组分到有限数量的桶里,然后
寻访序列,并且把项目一个一个放到对应的桶子去,对每个不是空的桶子进行排序,最终将所有的桶合并.
核心代码:
<pre><code>` func sort(arr:inout [Int],min:Int,max:Int,gap:Int) {
var bucketlist:[[Int]] = []
let bucketCount:Int = (max - min) / gap + 1
// 建桶
for _ in 0..<bucketCount {
let temp:[Int] = []
bucketlist.append(temp)
}
// 分桶
for i in 0..<arr.count {
let index:Int = (arr[i] - min) / gap
bucketlist[index].append(arr[i])
}
// 小桶排序
for i in 0..<bucketCount {
if bucketlist[i].count > 0 {
buketInnerSort(arr: &bucketlist[i])
}
}
var index:Int = 0
for i in 0..<bucketCount {
var bucket:[Int] = bucketlist[i]
if bucket.count > 0 {
for j in 0..<bucket.count {
arr[index] = bucket[j]
index += 1
}
}
}
}
private func buketInnerSort(arr:inout [Int]) {
let count:Int = arr.count
for i in 1..<count {
for j in (1...i).reversed() {
if arr[j] < arr[j-1] {
swap(&arr[j], &arr[j-1])
}
}
}
}`</code></pre>
测试代码:
<pre><code>let bucketSort:BucketSort = BucketSort() var arr:[Int] = [-10, -9, -20, 29, 25, 3, 49, 9, 37, 21, 43] bucketSort.sort(arr: &arr, min: -20, max: 50, gap: 10) print("FlyElephant--桶排序---\(arr)")
</code></pre>