我想实现计数排序,但想通过自定义对象实现。这在Swift中,但是实现细节不是太重要。
我想对一个基本上只包含一个整数(键)和一个字符的对象进行排序。
class ToSort : CustomStringConvertible {
var description: String {
return String(num)
}
var num : Int
var val : Character
init(_ num: Int, _ val : Character) {
self.num = num
self.val = val
}
}
现在通常存储整数的频率(https://www.geeksforgeeks.org/counting-sort/)。我想存储我的对象-我不确定该怎么做。我花了一些时间来寻找实现(带有自定义对象-我在上面有一个标准实现的链接),找不到一个,也无法弄清楚我应该如何实现这一点...
我想我可以通过实现字典(哈希映射)来做到这一点,但是如果我这样做的话,使用计数丢失的好处是什么?
答案 0 :(得分:1)
您可以尝试使用我实现的该算法以使用自定义对象,该算法可能会让您了解其实现方式,
struct Foo {
var number: Int
var name: String
}
enum CountingSortError: Error {
case arrayEmpty
}
func countingSort(array: [Foo]) throws -> [Foo] {
guard array.count > 0 else {
throw CountingSortError.arrayEmpty
}
// Step 1
// Create an array to store the count of each element
let maxElement = array.max{ a, b in a.number < b.number } ?? Foo(number: 0, name: "Zero")
var countArray = [Int](repeating: 0, count: Int(maxElement.number + 1))
for element in array {
countArray[element.number] += 1
}
// Step 2
// Set each value to be the sum of the previous two values
for index in 1 ..< countArray.count {
let sum = countArray[index] + countArray[index - 1]
countArray[index] = sum
}
print(countArray)
// Step 3
// Place the element in the final array as per the number of elements before it
let count = array.count
var sortedArray = [Foo](repeating: Foo(number: 0, name: ""), count: count)
sortedArray = array.sorted(by: { (a, b) -> Bool in
countArray[a.number] -= 1
return a.number < b.number
})
return sortedArray
}
用法:
print(try countingSort(array: [Foo(number: 10, name: ""), Foo(number: 9, name: ""), Foo(number: 8, name: ""), Foo(number: 7, name: ""), Foo(number: 1, name: ""), Foo(number: 2, name: ""), Foo(number: 7, name: ""), Foo(number: 3, name: "")]).flatMap {$0.number})
输出
count [0, 1, 2, 3, 3, 3, 3, 5, 6, 7, 8]
sorted [1, 2, 3, 7, 7, 8, 9, 10]
基本算法code