当前位置:网站首页>带你了解直接插入排序(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;
}
}
边栏推荐
- Use cache to reduce network requests
- JS interview questions - arrow function, find and filter some and every
- 软件项目管理 7.1.项目进度基本概念
- 2022 | framework for Android interview -- Analysis of the core principles of binder, handler, WMS and AMS!
- 軟件項目管理 7.1.項目進度基本概念
- Template engine - thymeleaf
- 中文输入法输入事件composition的使用
- Typescript compilation options and configuration files
- The tutor transferred me 800 yuan and asked me to simulate a circuit (power supply design)
- 统计出现次数最多的前K个字符串
猜你喜欢

Uncaught TypeError: Cannot set property ‘next‘ of undefined 报错解决

It will be too late if you don't brush the questions. The most complete bat interview questions

广东市政安全施工资料管理软件2022新表格来啦

Intl.NumberFormat 设置数字格式

解决swagger文档接口404的问题

Uncaught typeerror: cannot set property 'next' of undefined
![[file upload vulnerability 05] server suffix detection and bypass experiment (based on upload-labs-3 shooting range)](/img/f5/52bc5e01bb0607b6ecab828fb70c93.jpg)
[file upload vulnerability 05] server suffix detection and bypass experiment (based on upload-labs-3 shooting range)

ELK - X-Pack设置用户密码

Use of Chinese input method input event composition

MYCAT sub database and sub table
随机推荐
Use compiler option ‘--downlevelIteration‘ to allow iterating of iterators 报错解决
[JUC supplementary] atomic class, unsafe
苹果MobileOne: 移动端仅需1ms的高性能骨干
Modify WordPress management account name plug-in: admin rename extended
让WordPress支持注册用户上传自定义头像功能
WordPress用户名修改插件:Username Changer
WordPress user name modification plug-in: username changer
Jest unit test description config json
《公司理财师专业能力》笔记
吊打面试官,涨姿势
【Go】Gin源码解读
WordPress landing page customization plug-in recommendation
Pan domain SSL certificate, sectigo cheap wildcard certificate popularization plan
什么是Gerber文件?PCB电路板Gerber文件简介
Hamiltonian graph
The no category parents plug-in helps you remove the category prefix from the category link
[fragmentary thoughts] thoughts on wavelength, wave velocity and period
POJ 3278 catch the cow (width first search, queue implementation)
JS interview questions - arrow function, find and filter some and every
CVPR 2022 𞓜 text guided entity level image manipulation manitrans