Chapter 27: O(n²) Sorting Challenges
extension MutableCollection where Self: BidirectionalCollection, Element: Equatable {
mutating func rightAlign(value: Element) {
// 用兩個指針來分別紀錄左右兩邊的邊界位置
var left = startIndex
var right = index(before: endIndex)
// time: O(n)
while left < right {
// 右邊的值等於value
while self[right] == value {
// right指針仼左移
formIndex(before: &right)
}
while self[left] != value {
// left指針繼續移動
formIndex(after: &left)
}
guard left < right else {
return
}
swapAt(left, right)
}
}
}Last updated