插入排序

Posted by Chenyawei on 2019-12-05
Words 197 and Reading Time 1 Minutes
Viewed Times

直接插入思路:

每趟将一个待排序的关键字按照其值的大小,插入到有序序列中的正确的位置,直到全部序列有序。其时间复杂度为, 待排序的元素超过的规模时是无法承受的。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <cstdio>
#include <algorithm>

template <class T>
int getArrayLen(T&array){
return sizeof(array) / sizeof(array[0]);
}

//插入排序的代码
void insertSort(int A[],int n){
for(int i = 1; i<= n; i++){
int temp = A[i], j = i;
while(j>0 && temp < A[j - 1]){
A[j] = A[j - 1];
j--;
}
A[j] = temp;
}
}

int main(){

int A[] = {6,3,5,2,1,4};
int n = getArrayLen(A);
insertSort(A,n);
for(int i = 0; i < n; i++){
printf("%d\n",A[i]);
}
return 0;
}

notice

欢迎访问 chenyawei 的博客, 若有问题或者有好的建议欢迎留言,笔者看到之后会及时回复。 评论点赞需要github账号登录,如果没有账号的话请点击 github 注册, 谢谢 !

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !