File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 16
16
17
17
![ 动图演示] ( res/selectionSort.gif )
18
18
19
+ ``` cpp
20
+ void changeValue (int * a, int * b)
21
+ {
22
+ int temp = * a;
23
+ * a = * b;
24
+ * b = temp;
25
+ }
26
+ /*
27
+ 选择排序,升序排列
28
+ O(N^2)时间复杂度,O(1)空间复杂度
29
+ * /
30
+ vector<int > AlgorithmSort::selectionSort(vector<int > vec)
31
+ {
32
+ int len = vec.size();
33
+ int min = 0;
34
+ //边界值判定
35
+ if (len <= 1)
36
+ return vec;
37
+
38
+ //原始写法
39
+ //for (int i = 0; i < len; i++)
40
+ //{
41
+ // for (int j = i+1; j < len; j++)
42
+ // {
43
+ // if (vec[i] > vec[j])
44
+ // changeValue(&vec[i], &vec[j]);
45
+ // }
46
+ //}
47
+
48
+ //优化写法
49
+ for (int i = 0; i < len-1; i++)
50
+ {
51
+ // 取最小元素
52
+ vector<int>::iterator it = min_element(vec.begin() + i + 1, vec.end());
53
+ if(vec[i]>*it)
54
+ changeValue(&vec[i], &vec[it-vec.begin()]);
55
+ }
56
+ return vec;
57
+ }
58
+ ```
19
59
20
60
## 3. JavaScript 代码实现
21
61
You can’t perform that action at this time.
0 commit comments