当前位置:网站首页>带你了解直接插入排序(C语言)
带你了解直接插入排序(C语言)
2022-06-11 11:41:00 【Butayarou】
引入:
其实它和玩扑克牌的原理是一样的(用升序来举例):先拿第一张牌,再拿第二张牌,从后往前比较,此时只能与第一张牌比较(如果第二张牌的点数更大,把它放在第一张牌的后面,否则放在前面),然后拿第三张牌,将它从后往前比较,把它插入到合适的位置,使手上的牌仍然保持升序,接下来的牌都跟前面的操作相同。
基本思路:让 end 指向第一个数,先用 tmp 保存下标为(end + 1)的数,再将 tmp 依次与
下标从 end 到 0 的数(从后往前)比较(符号方向依是升序还是降序来定,且该步需要挪动元素),把 tmp 存的值插入到合适的位置。
将上面的基本思路做成一个循环(让 end 的指向范围为 [ 0 , n-1 ] )
可以发现,
手上现有的牌 ---------------->下标从 0 到 end 的元素tmp ----------------> 新拿的一张牌
从后往前比较,将牌插入到合适的位置 ----------------> 将 tmp 与 下标从 end 到 0
的元素比较(需要挪动元素),把 tmp 存的值插入到合适的位置
于是,每执行完一次循环后,下标从 0 到 end 的元素都是有序的。
代码实现
void InsertSort(int* a,int n)
{
for (int i = 0; i < n - 1;i++)
{
int end = i; //赋值给end,使得end位置后移,外扩
int tmp = a[end + 1];
while (end >= 0)
{
if (a[end] > tmp)
{
a[end + 1] = a[end];
end--; //靠end后退来实现两数比较
}
else
break;
}
a[end + 1] = tmp;
}
}
边栏推荐
- What is the latest popular annuity insurance product with higher income in 202?
- 异或的妙用(C语言)
- How should ordinary people choose annuity insurance products?
- JVM class loading process
- Maximum water container
- Mongodb usage
- [C language] anonymous/unnamed struct & Union
- WordPress landing page customization plug-in recommendation
- MSF CS OpenSSL traffic encryption
- 实用WordPress插件收集(更新中)
猜你喜欢

Node connects to MySQL database and writes fuzzy query interface

Uncaught typeerror: cannot set property 'next' of undefined

软件项目管理 7.1.项目进度基本概念

Iframe value transfer
![[JUC supplementary] atomic class, unsafe](/img/24/e51cfed39fe820fb46cca548af1782.jpg)
[JUC supplementary] atomic class, unsafe

The complete manual of the strongest Flink operator is a good choice for the interview~

C# 将OFD转为PDF

Intermediate web development engineer, interview questions + Notes + project practice

Elk - hearthbeat implements service monitoring

Gerber文件在PCB制造中的作用
随机推荐
js合并两个对象(面试题)
WordPress database cache plug-in: DB cache Reloaded
Interview experience of Xiaomi Android development post~
[C language] anonymous/unnamed struct & Union
[JUC supplementary] immutable object, shared meta mode, final principle
安全工程师发现PS主机重大漏洞 用光盘能在系统中执行任意代码
Intl.NumberFormat 设置数字格式
WP super cache static cache plug-in concise tutorial
WordPress重新生成特色图像插件:Regenerate Thumbnails
Runtime reconfiguration of etcd
C# 设置或验证 PDF中的文本域格式
[go] interpretation of gin source code
typescript 编译选项和配置文件
Maximum water container
Use cache to reduce network requests
National multi-year solar radiation spatial distribution data 1981-2022, temperature distribution data, evapotranspiration data, evaporation data, rainfall distribution data, sunshine data, wind speed
软件项目管理 7.1.项目进度基本概念
No category parents插件帮你去掉分类链接中的category前缀
Add auto thumbnail function for WordPress related log plug-ins
Intl.numberformat set number format