algo/swift/11_sorts/Sorts.swift
2018-10-16 00:05:55 +08:00

82 lines
1.8 KiB
Swift

import Foundation
///
///
/// - Parameter elements:
/// - Returns:
public func bubbleSort<T>(_ elements: [T]) ->[T] where T: Comparable {
var array = elements
guard array.count > 1 else {
return array
}
for i in 0..<array.count {
// 退
var flag = false
for j in 0..<array.count - i - 1 {
if array[j] > array[j+1] {
array.swapAt(j+1, j)
//
flag = true
}
}
if (!flag) {
break
}
}
return array
}
///
///
/// - Parameter elements:
/// - Returns:
public func insertionSort<T>(_ elements: [T]) -> [T] where T: Comparable {
var array = elements
guard array.count > 1 else {
return array
}
for i in 1..<array.count {
let value = array[i]
var j = i - 1;
//
for p in (0...j).reversed() {
j = p
if array[p] > value {
array[p+1] = array[p]
} else {
break
}
}
array[j+1] = value
}
return array
}
///
///
/// - Parameter elements:
/// - Returns:
public func selectionSort<T>(_ elements: [T]) -> [T] where T: Comparable {
var array = elements
guard array.count > 1 else {
return array
}
for i in 0..<array.count {
//
var minIndex = i
var minValue = array[i]
for j in i..<array.count {
if array[j] < minValue {
minValue = array[j]
minIndex = j
}
}
//
array.swapAt(i, minIndex)
}
return array
}