当前位置:网站首页>Sort--排序中的 插入排序 和 希尔排序
Sort--排序中的 插入排序 和 希尔排序
2022-07-22 04:25:00 【Placideo】
1.InsertSort--插入排序(先拆成单趟的,再走整体)
思路:拆成单趟的,再写整体的
时间复杂度:O(N^2)
最优情况:接近顺序有序 O(N)
最坏情况:逆序 O(N^2)
void InsertSort(int* a, int n)
{
for (int i = 0; i < n - 1; ++i)
{
// [0,end]有序,把end+1位置的值插入,保持有序
int end = i;
int tmp = a[end + 1];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + 1] = a[end];
--end;
}
else
{
break;
}
}
a[end + 1] = tmp;
}
}
2.ShellSort--希尔排序


思路:1.第一步--预排序(接近有序)
2.第二步--直接插入排序(有序)
void ShellSort(int* a, int n)//针对数据量大的
{
//一趟的插入
/*int gap = 3;*/
/*for (int j = 0; j < gap; ++j)
{
for (int i = j; i < n - gap; i += gap)
{
int end = i;
int tmp = a[end + gap];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + gap] = a[end];
end -= gap;
}
else
{
break;
}
}
a[end + gap] = tmp;
}
}*/
//多趟的插入
// gap > 1时是预排序
// gap 最后一次等于1,是直接插入排序
int gap = n;
while (gap > 1)
{
gap = gap / 3 + 1;
for (int j = 0; j < gap; ++j)//先完成一个的,再完成另一个
{
for (int i = j; i < n - gap; i += gap)
{
int end = i;
int tmp = a[end + gap];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + gap] = a[end];
end -= gap;
}
else
{
break;
}
}
a[end + gap] = tmp;
}
}
}
//多趟的插入
// gap > 1时是预排序
// gap 最后一次等于1,是直接插入排序
int gap = n;
while (gap > 1)
{
gap = gap / 3 + 1;
for (int i = 0; i < n - gap; ++i)//gap组数据交替插入排序(优化)
{
int end = i;
int tmp = a[end + gap];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + gap] = a[end];
end -= gap;
}
else
{
break;
}
}
a[end + gap] = tmp;
}
}
}
边栏推荐
猜你喜欢
The LAAS solution of elephant swap has risen rapidly and built a new defi2.0 protocol
Simulation Implementation of string
MP查询条件
交換機與路由器技術:標准ACL、擴展ACL和命名ACL
Session sharing problem
JVM memory model: classification and acquisition of class loaders
Elephant Swap的LaaS方案迅速崛起,构建全新DeFi2.0协议
When the easycvr platform cascades, there is an error prompt. What is the reason why the port is unreachable?
AlterNET脚本编写,用户界面设计功能
Figure calculation - figure introduction
随机推荐
6-12漏洞利用-枚举smtp用户名
Switch and router technology: Standard ACL, extended ACL and named ACL
C ftp detects whether the directory exists and creates a folder
NFT exchange contract development tutorial (solidity & hardhat)
AT5662 [AGC040D] Balance Beam(二分)
Popular science | how to create a Dao?
string的模拟实现
Hybrid hybrid development and jsbridge
Detailed explanation of PN communication between botu PLC and ABB Inverter
How to configure webrtc protocol for low latency playback on easycvr platform v2.5.0 and above?
[ssm]ssm integration ① (integration configuration)
The LAAS solution of elephant swap has risen rapidly and built a new defi2.0 protocol
Simulation Implementation of string
At5662 [agc040d] balance beam (two points)
Mock模拟数据,并发起get,post请求(保姆级教程,一定能成功)
window开机启动增加/关闭
Network layer interview questions
C # upload files to shared folders
MP查询条件
[solution] solve the importerror: library "Glu" not found