You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.5 KiB
49 lines
1.5 KiB
2 years ago
|
## 选择排序
|
||
|
### 一、前置知识
|
||
|
|
||
|
#### C++求整数数组长度的办法
|
||
|
```c++
|
||
|
int len = sizeof(a) / sizeof(int);
|
||
|
```
|
||
|
### 二、视频教程
|
||
|
[三分钟搞定选择排序(图解+动画演示)](https://www.bilibili.com/video/BV1J34y177bM)
|
||
|
|
||
|
### 三、算法总结
|
||
|
#### 算法思路
|
||
|
每次挑选最小的数和 <font color='red' size=4><b>未确定</b></font> 的 <font color='black' size=4><b>首个数字</b></font> <font color='blue' size=4><b>交换</b></font>。
|
||
|
|
||
|
#### 算法步骤
|
||
|
|
||
|
* 枚举每一个数字$a[i]$
|
||
|
* 枚举$i$后面的所有数字,找出$i$后面所有数字中最小的数字。
|
||
|
* 将找到的最小数字与$a[i]$交换
|
||
|
|
||
|
<font color='red' size=4><b>注:需要注意边界,第一层循环最多到$n-1$</b></font>
|
||
|
|
||
|
### 四、代码实现
|
||
|
|
||
|
```c++
|
||
|
#include <bits/stdc++.h>
|
||
|
|
||
|
using namespace std;
|
||
|
//选择排序
|
||
|
int a[] = {4, 1, 9, 5, 1, 7, 2};
|
||
|
int main() {
|
||
|
// C++求整数数组长度的办法
|
||
|
int len = sizeof(a) / sizeof(a[0]);
|
||
|
|
||
|
for (int i = 0; i < len - 1; i++) {
|
||
|
int min = i;
|
||
|
for (int j = i + 1; j < len; j++)
|
||
|
if (a[j] < a[min]) min = j;
|
||
|
swap(a[i], a[min]);
|
||
|
}
|
||
|
|
||
|
for (int i = 0; i < len; i++) cout << a[i] << " ";
|
||
|
return 0;
|
||
|
}
|
||
|
```
|
||
|
### 五、问题
|
||
|
$Q:$既然要找最小值,为什么不直接用$min$记录最小值,而是记录的是最小值对应的位置呢?
|
||
|
$A$:只记录最小值,确实可以把未确定的首个数字修改为最小值,但,首个数字就不知道放到哪里去了~
|