多条件快速排序

时间:2021-06-22 05:18:47

标签: swift sorting

我的排序要求有一些特殊条件。

class Man {
    var id: Int = 0
    var name: String = ""
    var childIds: [Man]()
    var parent: Man?
}

其实道理很简单。 如果对象没有子/父对象,则它遵循升序名称。但是如果对象有孩子,孩子必须在他之下。 下面是示例预期输出,带有 > 的名称表示它是一个孩子,上面的名称是 parent。我尝试了几种方法,但仍然无法为子/父关系设置特定顺序。


安迪
鲍勃
>亚历克斯
辛迪
>本

1 个答案:

答案 0 :(得分:1)

你的模型应该有什么?

import Foundation

class Person: CustomStringConvertible {
    let id: Int
    let name: String
    let childrenIDs: [Int]
    let parent: Person?
    
    init(id: Int, name: String, childrenIDs: [Int] = [], parent: Person? = nil) {
        self.id = id
        self.name = name
        self.childrenIDs = childrenIDs
        self.parent = parent
    }
    
    var description: String {
        "<id: \(id), name: \(name)>"
    }
    
    var sortingName: String {
        "\(parent?.name ?? "")\(name)"
    }
}

如何使用它进行排序?

let cindy = Person(id: 4, name: "Cindy", childrenIDs: [5], parent: nil)
let ben = Person(id: 5, name: "Ben", childrenIDs: [], parent: cindy)
let andy = Person(id: 1, name: "Andy")
let bob = Person(id: 2, name: "Bob", childrenIDs: [3], parent: nil)
let alex = Person(id: 3, name: "Alex", childrenIDs: [], parent: bob)

let persons: [Person] = [ben, cindy, andy, alex, bob]
let sortedPersons = persons.sorted(by: { p1, p2 in
    p1.sortingName.compare(p2.sortingName) == .orderedAscending
})
print(sortedPersons)

输出

[
  <id: 1, name: Andy>,
  <id: 2, name: Bob>,
  <id: 3, name: Alex>,
  <id: 4, name: Cindy>,
  <id: 5, name: Ben>
]