<피벗보다 작은 요소 | 피벗 | 피벗보다 큰 요소>
public func quicksortNaive<T: Comparable>(_ a:[T]) -> [T] {
guard array.count >= 2 else {
return array
}
let pivot = array[a.count / 2]
let less = array.filter { $0 < pivot}
let equal = array.filter { $0 == pivot}
let greater = array.filter { $0 > pivot}
return quicksortNaive(less) + equal + quicksortNaive(greater)
}
private func partitionLomuto<T: Comparable>(_ a: inout[T], low: Int, high: Int) -> Int {
let pivot = a[high]
var i = low
for j in low..<high {
if a[j]<= pivot {
a.swapAt(i, j)
i += 1
}
}
a.swapAt(i, high)
return i
}
public func quicksortLomuto<T: Comparable>(_ a: inout [T], low: Int, high: Int) {
if low < high {
let pivot = partitionLomuto(&a, low: low, high: high)
quicksortLomuto(&a, low: low, high: pivot - 1)
quicksortLomuto(&a, low: pivot + 1, high: high)
}
}
private func partitionHoare<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int {
let pivot = a[low]
var i = low - 1
var j = high + 1
while true {
repeat { j -= 1 } while a[j] > pivot
repeat { i += 1 } while a[i] < pivot
if i < j {
a.swapAt(i, j)
} else {
return j
}
}
}
public func quicksortHoare<T: Comparable>(_ a: inout [T], low: Int, high: Int) {
if low < high {
let pivot = partitionHoare(&a, low: low, high: high)
quicksortHoare(&a, low: low, high: pivot)
quiclsortHoare(&a, low: pivot +1, high: high)
}
}
public func medianOfThree<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int {
let center = (low + high) / 2
if a[low] > a[center] {
a.swapAt(low, center)
}
if a[low] > a[high] {
a.swapAt(low, high)
}
if a[center] > a[high] {
a.swapAt(center, high)
}
return center
}
private func partitionDutchFlag<T: Comparable>(
_ a: inout [T],
low: Int,
high: Int,
pivotIndex: Int
) -> (Int, Int) {
let pivot = a[pivotIndex]
var smaller = low
var equal = low
var larger = high
while equal <= larger {
if a[equal] < pivot {
a.swapAt(smaller, equal)
smaller += 1
equal += 1
} else if a[equal] == pivot {
equal += 1
} else {
a.swapAt(equal, larger)
larger -= 1
}
}
return (smaller, larger)
}
public func quicksortDutchFlag<T: Comparable>(_ a: inout [T], low: Int, high: Int) {
if low < high {
let pivot = medianOfThree(&a, low: low, high: high)
let (middelFirst, middelLast) = partitionDutchFlag(
&a,
low: low,
high: high,
pivotIndex: pivot
)
quicksortDutchFlag(&a, low: low, high: middelFirst - 1)
quicksortDutchFlag(&a, low: middelLast + 1, high: high)
}
}
var list3 = [4,123,14,2,33,12,1,42,11,67,8,84,9]
quicksortDutchFlag(&list3, low: 0, high: list3.count - 1)
print(list3)
[1, 2, 4, 8, 9, 11, 12, 14, 33, 42, 67, 84, 123]
제가 학습한 내용을 요약하여 정리한 것입니다. 내용에 오류가 있을 수 있으며, 어떠한 피드백도 감사히 받겠습니다.
감사합니다.