选择排序

Posted by アライさん on 2019年10月22日

选择排序效率为O( n × 1/ 2 × n)。
省略常数之后变成O(n*n)

遍历列表,选择最小值,排到第一位。从第二位开始,遍历列表……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
fun main(args: Array<String>) {
var aaaa = ArrayList<Int>()
aaaa.add(5)
aaaa.add(3)
aaaa.add(6)
aaaa.add(2)
aaaa.add(10)
print(selectionSort(aaaa))
}



//从一个数组中取最小值
fun findSmallest(arrayList:ArrayList<Int>) : Int{
var smallest = arrayList[0]//最小元素
var smallest_index = 0//最小元素索引
for(i in arrayList.indices){
if(arrayList[i] < smallest){
smallest = arrayList[i]
smallest_index = i9
}
}
return smallest_index
}

//排序
fun selectionSort(arrayList:ArrayList<Int>):ArrayList<Int>{
var newArrayList = ArrayList<Int>()

for(i in arrayList.indices){
var index = findSmallest(arrayList)
newArrayList.add(arrayList[index])
arrayList.remove(arrayList[index])
}

return newArrayList
}
</code></pre>
<br>
## dart版本
<pre><code> //选择排序
selectSort(List<int> list){
for(int i = 0; i < list.length - 1; i++){
int largerIndex = findLargerIndex(list, i);
int temp = list[largerIndex];
list[largerIndex] = list[i];
list[i] = temp;
}
}

//找出最大值
int findLargerIndex(List<int> list,int startIndex){
int larger = list[startIndex];
int largerIndex = startIndex;
for(int i = startIndex +1 ; i< list.length;i++){
if(larger < list[i] ){
larger = list[i];
largerIndex = i;
}
}

return largerIndex;
}