public func bubbleSort<Element>(_ array: inout[Element]) where Element: Comparable {
guard array.count >= 2 else {
return
}
for end in (1..<array.count).reversed() {
var swapped = false
for current in 0..<end {
if array[current] > array[current + 1] {
array.swapAt(current, current + 1)
swapped = true
}
}
if !swapped {
return
}
}
}
var array1 = [9,4,10,3]
bubbleSort(&array1)
[3,4,9,10]
public func selectionSort<Element>(_ array: inout [Element]) where Element: Comparable {
guard array.count >= 2 else {
return
}
for current in 0..<(array.count - 1) {
var lowest = current
for other in (current + 1)..<array.count {
if array[lowest] > array[other] {
lowest = other
}
}
if lowest != current {
array.swapAt(lowest, current)
}
}
}
var array2 = [9,4,10,3]
selectionSort(&array2)
[3,4,9,10]
public func insertionSort<Element>(_ array: inout [Element]) where Element: Comparable {
guard array.counr >= 2 else {
return
}
for current in 1..<array.count {
for shifting in (1...currnet).reversed() {
if array[shifting] < array[shifting - 1] {
array.swapAt(shifting, shifting - 1)
} else {
break
}
}
}
}
제가 학습한 내용을 요약하여 정리한 것입니다. 내용에 오류가 있을 수 있으며, 어떠한 피드백도 감사히 받겠습니다.
감사합니다.