Sorting algorithms implemented in swift
final class Sort {
private static func swapped<T: Comparable>(_ first: T, _ second: T) -> (first: T, second: T) {
return (second, first)
}
// BubbleSort is O(n^2)
static func bubbleSort<T: Comparable>(_ array: [T]) -> [T] {
var resultArray = array
if resultArray.count < 2 {
return resultArray
}
var isSwapped: Bool
repeat {
isSwapped = false
for i in 0 ..< resultArray.count-1 {
if resultArray[i] > resultArray[i+1] {
let swapped = Sort.swapped(resultArray[i], resultArray[i+1])
resultArray[i] = swapped.first
resultArray[i+1] = swapped.second
isSwapped = true
}
}
} while isSwapped
return resultArray
}
}
Sort.bubbleSort([2,4,1,6,3])