选择排序(Selection Sort)会在在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后继续以上过程,直至所有的元素排序完毕,代码实现:
func selectionSort(inout arr: Array<NSInteger>) {
for i in 0.stride(to: arr.count-1, by: 1) {
var minIndex = i
for j in (i+1).stride(to: arr.count, by: 1) {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
let temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
}
}
var data = [3,8,10,2,9,5,1,100]
selectionSort(&data)
print("\(data)")
方案2
func sort(arr:inout [Int]) {
let count:Int = arr.count
for i in 0..<count {
var minIndex:Int = i
for j in i..<count {
if arr[minIndex] > arr[j] {
minIndex = j
}
}
if i != minIndex {
swap(&arr[i], &arr[minIndex])
}
}
}