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.
1.8 KiB
1.8 KiB
插入排序
插入排序是简单排序中效率最好的一种,它也是学习其他高级排序的基础,比如希尔排序/快速排序,所以非常重要,而它相对于选择排序的优点就在于比较次数几乎是少了一半。
### 一、算法思路
- 从第一个元素开始,该元素可以认为已经被排序。
- 取出下一个元素,在已经排序的元素序列中从后向前扫描。
- 如果该元素(已排序)大于新元素,则将该元素移动到下一个位置。
- 重复上一个步骤,直到找到已排序的元素小于或者等于新元素的位置,将新元素插入到该位置后,重复上面的步骤。


二、算法实现
#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;
}