当前位置:网站首页>插入排序
插入排序
2022-06-12 21:01:00 【又秃又弱】
插入排序:(小的往前走)
思想:
无序序列: 4 2 3 5 7 1 9 2 0
i j //i、j对应指向上面的数字(不知道箭头符号在哪就没有画出来)
temp=2(j) 4>2,4后移 j++
2 4 3 5 7 1 9 2 0 //标红为已排序
i j //i之前有序
temp=3 3<4,4赋值到3的位置 i--
2 4 4 5 7 1 9 2 0
i j
2<3,不交换 3->i+1的位置 j++,i->j-1
2 3 4 5 7 1 9 2 0
i j
temp=5 (i的值)4<5,i前面就不用再比了 j++,i->j-1;
2 3 4 5 7 1 9 2 0
i j
temp=7; 5<7,不用再交换了
2 3 4 5 7 1 9 2 0
i j
temp=1; 7>1; 7->j+1位置 i--;
.... 2>1; 5->i+1位置
i-1=-1<0;//停止条件
temp->i+1 j++;i->j-1
1 2 3 4 5 7 9 2 0
i j
.....
0 1 2 2 3 4 5 7 9
代码实现:
//插入排序
int InsertSort(int arr,int length) {
for (int j = 1; j < length; j++)
{
int i = j - 1;
int temp = arr[j];
for (;arr[i] >temp && i>=0;i--) //arr[i] >arr[j]错误,每次j都改变啦
{
arr[i+1] = arr[i];
}//i退出的时候是-1或者当前arr[i]>arr[j]
//if(arr[i] <= arr[j] || i = 0)
arr[i+1] = temp;
}
}
int main() {
int arr[] = { 4,2,3,5,7,1,9,2,0 };
InsertSort(arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}
边栏推荐
- How to download putty using alicloud image?
- [tutorial] Firefox send: deployment method of Firefox open source temporary file sharing service platform
- How can CTCM in the inspection lot system status of SAP QM be eliminated?
- 中小型机房动力环境综合监控解决方案
- Unauthorized rce in VMware vCenter
- torch. nn. Linear() function
- shell语言
- 初步了解认识正则表达式(Regex)
- How do testers plan for their future? To achieve 25K in 2 years?
- Li Mu [practical machine learning] 1.4 data annotation
猜你喜欢

How mysterious is "PIP not an internal or external command, nor a runnable program or batch file"

Data visualization - broken line area chart

多机房动环状态网络触摸屏监控解决方案

Leetcode: 210. Programme II

Image processing 12- image linear blending

没有学历,自学软件测试,找到一份月入过万的测试工作真的有可能吗?

leetcode:210. 課程錶 II

JSP中的监听器

Solve the cvxpy error the solver GLPK_ MI is not installed

leetcode:207. 课程表
随机推荐
做自媒体视频,友好的新媒体运营必备app分享
new做了哪几件事
Understanding of functions
torch. unique()
[tutorial] Firefox send: deployment method of Firefox open source temporary file sharing service platform
MySQL field truncation principle and source code analysis
Library cache lock brought by add trandata
To understand Devops, you must read these ten books!
Leetcode: 210. Programme II
Event distribution mechanism of view
Detect current system language
remote: Support for password authentication was removed on August 13, 2021
Composer version degradation
Lombok package is successfully installed, but the runtime prompts that get, set method and constructor solution cannot be found
Why my order by create_ Time ASC becomes order by ASC
作用域和作用域链
How to implement overloading in JS
SAP QM preliminary - cannot assign a sampling policy to an inspection characteristic when maintaining an inspection plan by executing transaction code qp02?
Before job hopping, Jin San made up the interview questions. Jin San successfully landed at Tencent and got a 30K test offer
#886 Possible Bipartition