当前位置:网站首页>排序之插入排序
排序之插入排序
2022-07-28 05:18:00 【zhengyawen666】
一 算法思想
以排升序为例:
第一个数据看作是已经排序好了的数据,从下标为1的第二个数据开始排序,将该数据作为end。需要将end+1的数据插入到之前的数据里面去,以形成有序的数据。那么先开辟一个tmp的空间,把这一个数据先存储起来,以防止后续的数据整体后移以及插入的时候数据的消失。
将该tmp空间中存储的数据分别与之前的数据一一进行比较,如果tmp比之前的数据要小,那么就要将该位置的数据往后移动一个位置,tmp再与前面的数据进行比较。直至tmp>该位置的数据,那么就将数据插入该位置的下一个位置。(之前已经通过移动预留出了一个数据的位置)。
上述的操作是一次数据插入的操作,需要对所有的数据进行操作,因此在外面再套一层循环控制。
二 代码展示
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
void insertsort(int* pa, int size)
{
assert(pa);
int i = 0;
for (i = 1; i <size-1; i++)
{
int end = i;
int tmp = pa[end + 1];
while (end >= 0)
{
if (tmp < pa[end])
{
pa[end + 1] = pa[end];
end--;
}
else
{
break;
}
}
pa[end+1] = tmp;
}
}
int main()
{
int a[] = { 11,25,6,87,98,69,30,23,10,2 };
int size = sizeof(a) / sizeof(a[0]);
insertsort(a, size);
int i = 0;
for (i = 0; i < size; i++)
{
printf("%d ", a[i]);
}
return 0;
}边栏推荐
- Digital twin technology creates visual application of smart mine
- About localdatetime in swagger
- How Visio accurately controls the size, position and angle of graphics
- Openjudge: upper and lower case letters are interchanged
- Lamda gets the current number of cycles, atomicinteger
- Review of Metallurgical Physical Chemistry - gas liquid phase reaction kinetics
- Image enhancement - msrcr
- repackag failed: Unable to find main class
- ECCV22 最新54篇论文主图整理
- GET与POST区别
猜你喜欢

Multi module packaging: package: XXX does not exist

You must configure either the server or JDBC driver (via the ‘serverTimezone)

架构设计思考之一(SSO设计)

You must configure either the server or JDBC driver (via the ‘serverTimezone)

IDEA配置 service(Run Dashboard) 服务,多模块同时启动

Review of metallurgical physical chemistry --- liquid liquid reaction kinetics

蒙特卡罗方法求解圆周率π并用turtle画点,以及完成进度条问题

冶金物理化学复习 ---- 气固反应动力学

BigDecimal rounds and retains two decimal places

自定义Json返回数据
随机推荐
Multi module packaging: package: XXX does not exist
Distillation model diagram
latex使用\hl进行高亮时遇到引用总是报错,显示少了括号或者多了括号
Redis' bloom filter
Use of IO streams
The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem
BeanUtils. Copyproperties cannot copy different list sets problem solving lists.transform function
Openjudge: count the number of numeric characters
数据库面试
冶金物理化学复习 ---- 气固反应动力学
2021csdn blog star selection, mutual investment
Response<T>类
(黑马)MYSQL初级-高级笔记(博主懒狗)
mysql 为查询结果增加序号
CentOS7安装MySQL5.7
Edge calculation kubeedge+edgemash
冶金物理化学复习 --- 金属的电沉积,还原过程
JVM篇 笔记3:类加载与字节码技术
Digital twin solutions inject new momentum into the construction of chemical parks
集合框架的操作使用
