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.
63 lines
1.8 KiB
63 lines
1.8 KiB
2 years ago
|
## 冒泡排序
|
||
|
|
||
|
### 一、算法原理
|
||
|
<font color='red' size=4><b>
|
||
|
混沌未开之际,盘古大神开天辟地,清而轻的上升为天,浊而重的下沉为地。</b></font>冒泡排序就是类似把清(小)的上升,重(大)的下沉。
|
||
|
|
||
|
原理:就是像水中的泡泡一样,把每个数比作一个泡泡,相邻两个泡泡相互比较,较轻的一个就往上浮。最后就得到了一个有序的泡泡组合。
|
||
|
|
||
|
### 二、算法思路
|
||
|
小提示:假设从小排到大的方式,一轮比较下来最大的值就会跑到末尾位置,再次进行二轮比较后最大值排在末尾倒数第二位,依次类推...
|
||
|
|
||
|
所以就得出 $for$ 的判定条件是 $j < len - 1 - i$
|
||
|
|
||
|
### 三、视频讲解
|
||
|
[算法动画图解:三分钟学会冒泡排序算法](https://www.bilibili.com/video/av767891539)
|
||
|
|
||
|
### 四、由小到大
|
||
|
```c++
|
||
|
#include <bits/stdc++.h>
|
||
|
using namespace std;
|
||
|
|
||
|
int a[] = {1, 3, 5, 7, 9, 2, 4, 6, 8}; // 待排序数组
|
||
|
|
||
|
int main() {
|
||
|
int len = sizeof(a) / sizeof(int); // 数组长度
|
||
|
|
||
|
// 冒泡排序
|
||
|
for (int i = 0; i < len; i++)
|
||
|
for (int j = 0; j < len - 1 - i; j++)
|
||
|
if (a[j] > a[j + 1]) // 从小排到大
|
||
|
swap(a[j], a[j + 1]);
|
||
|
|
||
|
// 打印数组
|
||
|
for (int i = 0; i < len; ++i) cout << a[i] << " ";
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
```
|
||
|
|
||
|
### 五、由大到小
|
||
|
```c++
|
||
|
#include <bits/stdc++.h>
|
||
|
using namespace std;
|
||
|
|
||
|
int a[] = {1, 3, 5, 7, 9, 2, 4, 6, 8}; // 待排序数组
|
||
|
|
||
|
int main() {
|
||
|
int len = sizeof(a) / sizeof(int); // 数组长度
|
||
|
|
||
|
// 冒泡排序
|
||
|
for (int i = 0; i < len; i++)
|
||
|
for (int j = 0; j < len - 1 - i; j++)
|
||
|
if (a[j] < a[j + 1]) // 从大排到小
|
||
|
swap(a[j], a[j + 1]);
|
||
|
|
||
|
// 打印数组
|
||
|
for (int i = 0; i < len; i++) cout << a[i] << " ";
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
```
|