我可以正确插入O(n)中按字母顺序排序的列表吗?

时间:2018-10-30 16:57:57

标签: arrays swift algorithm

我正在尝试将运行时从O(nlgn)降为O(n)。现在,我将一个新的Person对象添加到通讯簿,然后进行排序,但我只想按字母顺序在正确的位置插入新的Person对象。最好的方法是什么?

// Swift 4.2
class Person {
    var fName: String
    var lName: String
    init(fName: String, lName: String) {
        self.fName = fName
        self.lName = lName
    }
}

var addressBook = [Person]()

var peopleToAdd: [Person] = [Person(fName: "John", lName: "Smith"),
                        Person(fName: "Joan", lName: "Smith"),
                        Person(fName: "Rick", lName: "Smith"),
                        Person(fName: "Adam", lName: "Beyers"),
                        Person(fName: "Alan", lName: "Beyers"),
                        Person(fName: "Nick", lName: "Johnson"),
                        Person(fName: "Dan", lName: "Johnson")].shuffled()

for person in peopleToAdd {
    addNewPersonAlphabetically(person: person)
}

func addNewPersonAlphabetically(person: Person) {
    // this is where the magic happens!
}


print(addressBook) // Should print an alphabetized list of Person objects

如果2个姓氏相同,则以名字开头。

如果我问一个已经回答过的问题,请原谅我:我尝试搜索,但大多数答案都只是排序。

谢谢!

0 个答案:

没有答案