插入排序(InsertSort)
来源:互联网 发布:亦强软件 编辑:程序博客网 时间:2024/05/06 16:43
首先举一个和插入排序有关的例子
现在桌上有一副扑克,要求我们要有序的放在手上,所以我们就要在拿牌的同时,用拿起来的牌与手中已经存在的牌作比较,并且之后把这张牌放在合适的位置。
所以,当我们面对的是一组数据的时候我们也可以使用这种思路来对这组数据进行排序。首先我们要拿出一个数字来做为与其他数据进行比较的“标志牌“(我自己这么称呼的- -。)并且把它放在小于它的最大整数的且数组中存在的数字的后面,大于它的最小整数且数组中存在的数字的前面,这也就是插入排序的核心。
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){ int a[10]; //随机生成一组数字用来检测排序算法 srand(time(NULL)); for(int i=0; i<10; i++) { a[i]=rand()%10+1; printf("%d ", a[i]); } printf("\n"); //插入排序 for(int i=1; i<10; i++) { int j=i-1; //相当于我们手上的牌的下标 int temp = a[i]; //我们要拿的牌 while(j>=0 && a[j]>temp){ a[j+1] = a[j]; //将大于temp的数字后移 j--; } a[j+1] = temp; //插入temp } //排序后的输出 for(int i=0; i<10; i++) { printf("%d ", a[i]); } printf("\n"); return 0;}
插入排序的时间复杂度是O(nlgn),不稳定的排序算法!如果有什么写的不好的地方大家可以评论,我会改正的!
0 0
- 插入排序(InsertSort)
- 插入排序(InsertSort)
- 插入排序(InsertSort)
- 插入排序算法(InsertSort)
- 插入排序(insertSort.cpp)
- 插入排序之直接插入(InsertSort)
- 内部排序之插入排序(InsertSort)
- 插入排序法(InsertSort)c++实现
- 插入排序InsertSort
- insertSort - 插入排序
- 插入排序 InsertSort
- 插入排序 InsertSort
- 插入排序InsertSort
- 插入排序-InsertSort
- java insertsort 插入排序
- 插入排序-insertsort
- InsertSort 插入排序算法
- 数据结构-插入排序InsertSort
- 简单工厂模式和工厂方法模式的区别
- mybatis配置文件中resultType和resultMap错写后将会封装成属性不一样数据,以及后台报错java.util.HashMap cannot be cast to com.entity
- Lua:如何将自己写的模块加入环境中
- Openvswitch原理与代码分析(7): 添加一条流表flow
- 【软考总结】——编译原理之文法
- 插入排序(InsertSort)
- 使用autoconfig/automake生成makefile文件以及将程序打包为tar.gz
- HTML中输入框禁止手动输入的属性
- 笨笨的小猪
- About——Java
- 关于欢迎使用Markdown编辑器写博客
- leetcode 357 Count Numbers with Unique Digits
- MatConvNet卷积神经网络(四)——用自己的数据训练
- arm汇编指令