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.
42 lines
1.8 KiB
42 lines
1.8 KiB
2 years ago
|
## 插入排序
|
||
|
|
||
|
插入排序是简单排序中效率最好的一种,它也是学习其他高级排序的基础,比如希尔排序/快速排序,所以非常重要,而它相对于选择排序的优点就在于比较次数几乎是少了一半。
|
||
|
|
||
|
### 一、算法思路
|
||
|
* 从第一个元素开始,该元素可以认为已经被排序。
|
||
|
* 取出下一个元素,在已经排序的元素序列中从后向前扫描。
|
||
|
* 如果该元素(已排序)大于新元素,则将该元素移动到下一个位置。
|
||
|
* 重复上一个步骤,直到找到已排序的元素小于或者等于新元素的位置,将新元素插入到该位置后,重复上面的步骤。
|
||
|
|
||
|
<center><img src='https://img-blog.csdnimg.cn/a6ea22d851bd4bf68e3ea4c3fa7ff5e1.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56eD5aS055qE56eR5q-U,size_15,color_FFFFFF,t_70,g_se,x_16#pic_center'></center>
|
||
|
|
||
|
<center><img src='https://img-blog.csdnimg.cn/41e84db61dc54dfa8f46ab4d643b9620.gif#pic_center'></center>
|
||
|
|
||
|
[点我](https://img-blog.csdnimg.cn/41e84db61dc54dfa8f46ab4d643b9620.gif#pic_center)
|
||
|
|
||
|
### 二、算法实现
|
||
|
```c++
|
||
|
#include <bits/stdc++.h>
|
||
|
|
||
|
using namespace std;
|
||
|
const int len = 10;
|
||
|
int a[] = {3, 5, 1, 7, 2, 4, 6, 9, 8, 0};
|
||
|
|
||
|
int main() {
|
||
|
//数组长度
|
||
|
int len = sizeof(a) / sizeof(int);
|
||
|
|
||
|
for (int i = 1; i < len; i++) {
|
||
|
int now = a[i]; //记录一下待插牌
|
||
|
int j = i - 1;
|
||
|
while (j >= 0 && a[j] > now) { //发现比待插入牌大
|
||
|
a[j + 1] = a[j]; //挪出位置
|
||
|
j--; //继续向前找
|
||
|
}
|
||
|
a[j + 1] = now; //放到合适的位置上
|
||
|
}
|
||
|
//输出
|
||
|
for (int i = 0; i < len; i++) printf("%d ", a[i]);
|
||
|
return 0;
|
||
|
}
|
||
|
```
|