0%

排序算法——选择排序

前言

自己动手实现一下各种算法,以后复习也不用到处搜索了

通俗一点

例如从小到大排序,每次假设未排序的首位为最小值,则最小位置为首位。遍历剩下所有未排序,如果发现有值比首位小,标记当前位置为最小位置,继续遍历。发现比最小位置的值还要小,更新此位置为最小位置。一轮循环结束,如果最小位置不为首位,交换两个位置数据。当前循环结束,首位已排序,下次从 +1 位置开始遍历。
如果数组个数为 N,则需要循环 N-1 次。

算法实现

Swift 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func selectionSort(array: inout [Int]) {
for index in 0..<array.count - 1{
//标记当前 index 为最小 index
var minIndex = index
for unSortedIndex in index + 1..<array.count {
if array[unSortedIndex] < array[minIndex] {
//如果发现更小的值,更新最小 index
minIndex = unSortedIndex
}
}
if minIndex != index {
let temp = array[index]
array[index] = array[minIndex]
array[minIndex] = temp
}
print("----------------第\(index+1)次循环后-------------------")
var numbers = ""
for number in array{
numbers.append(" \(number)")
}
print(numbers)
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
----------------第1次循环后-------------------
3 44 38 5 47 15
----------------第2次循环后-------------------
3 5 38 44 47 15
----------------第3次循环后-------------------
3 5 15 44 47 38
----------------第4次循环后-------------------
3 5 15 38 47 44
----------------第5次循环后-------------------
3 5 15 38 44 47

动画展示

selection

来自:visualgo