InsertSort 插入排序算法
来源:互联网 发布:win7系统优化 编辑:程序博客网 时间:2024/05/19 14:00
InsertSort 插入排序算法:
平均比较和移动次数为(n^2)/4,时间复杂度也为O(n^2)
直接插入排序比冒泡和简单选择排序的性能要好一些。
思路:
从第二个数开始遍历到最后一个数,如果当前的数小于前一个数,用tmp保存当前数,比较前面的数与tmp的大小,
如果比tmp大则将前面的数往后移动一位,最终将tmp存放在没有再比tmp数大的那个数的位置。
代码:
//插入排序(排序后为从小到大)#include <iostream>#include <algorithm>using namespace std;void InsertSort(int (&a)[7]){//数组作为引用形参传入,使用在此修改对原数组也有效int aSize = sizeof(a) / sizeof(a[0]);//取数组的大小 int tmp;//设置一个空变量,来保存当a[i]<a[i-1]时,a[i]的位置,防止被覆盖for (int i = 1; i < aSize; ++i){//从第二个数开始遍历if (a[i] < a[i - 1]){//如果当前数小于前一个数tmp = a[i];//保存当前数int j; for (j = i - 1; a[j]>tmp&&j >= 0; --j){//如果前面的数都小于当前数a[j + 1] = a[j];//将前面的这些数位置后移一位}a[j + 1] = tmp;//将这个a[i]放到没有比它大的数之前}}}int main(){ int a[] = {12, 42, 6, 17, 32, 4, 19 };cout << "Before Sorted:" << endl;for (size_t i = 0; i < 7; ++i){//输出 cout << a[i] << " ";}cout << endl;InsertSort(a);cout << "After Sorted:" << endl;for (size_t i = 0; i < 7; ++i){//输出cout << a[i] << " ";}cout << endl;return 0;}
程序输出:
0 0
- InsertSort 插入排序算法
- 排序算法-插入排序 insertSort
- 排序算法-InsertSort-插入排序
- 插入排序算法(InsertSort)
- 经典算法-插入排序Insertsort
- 算法学习----->Insertsort(插入排序)
- 经典排序算法(2) -插入排序 InsertSort
- 算法导论2.1-insertsort算法(插入排序)
- 算法与数据结构--插入排序(InsertSort)
- 插入排序InsertSort
- insertSort - 插入排序
- 插入排序 InsertSort
- 插入排序 InsertSort
- 插入排序(InsertSort)
- 插入排序InsertSort
- 插入排序-InsertSort
- java insertsort 插入排序
- 插入排序-insertsort
- [bzoj2152]聪明可可 点分治
- rk3288 lvds TF卡修改屏参
- lucene分布式架构-满足高并发的实时检索需求
- 关于处理NOClassDefFoundError-org/apache/logj4/logManager
- 原生JS实现图片的放大镜效果
- InsertSort 插入排序算法
- RDD,DataFrame与DataSet
- Spring Email-邮件发送
- Linux 中统计一个进程的线程数
- uva11100
- 脏标识模式
- junit 自带rule及rule扩展
- 解决Spring MVC @ResponseBody返回中文字符串乱码问题
- 【linux】命令安装jdk1.7