持續(xù)更新中...
環(huán)境:Mac+Swift4
GitHub源碼:swift-algorithm
import Foundation
class Sort{
//MARK: - 冒泡排序
//核心是兩次遍歷媳溺,里循環(huán)最大往右放进每,只遍歷到len-i-1
class func bubbleSort(array:[Int])->[Int]{
var newArray = array
for i in 0..<newArray.count{
for j in 0..<newArray.count-(i+1){
if newArray[j] > newArray[j+1]{
let temp = newArray[j]
newArray[j] = newArray[j+1]
newArray[j+1] = temp
}
}
}
return newArray
}
//MARK: - 選擇排序
//核心是兩次遍歷,里循環(huán)找最小復(fù)制給array[i],里面的順序是i+1到底
class func selectSort(array:[Int])->[Int]{
var newArray = array
let len = array.count
for i in 0..<len{
var min = newArray[i]
for j in (i+1)..<len{
if min > newArray[j]{
let temp = min
min = newArray[j]
newArray[j] = temp
}
}
newArray[i] = min
}
return newArray
}
}