插入排序
来源:互联网 发布:淘宝神兽金刚玩具 编辑:程序博客网 时间:2024/06/16 04:07
算法内容是《算法导论》第三版 伪代码的 C 实现
1. 排序算法灵感
We start with insertion sort, which is an efficient algorithm for sorting a small number of elements. Insertion sort works the way many people sort a hand of playing cards. We start with an empty left hand and the cards face down on the table. We then remove one card at a time from the table and insert it into the correct position in the left hand. To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left, as illustrated in Figure 2.1. At all times, the cards held in the left hand are sorted, and these cards were originally the top cards of the pile on the table.
总之排序算法的灵感来自于 扑克牌的理排过程。左手上的牌一直的按照非降序顺序排列的,每插入一个新的数据,和左手里的牌的一一匹配,直到找到合适的位置插入。
2. 排序算法的伪代码
Insertion-Sort(A):for j=2 to A.length key = A[ j ] // Insert A[j] into the sorted sequence A[1...j-1]. i = j-1 while i > 0 and A[i] > key A[i+1] = A[i] i = i - 1 A[i + 1] = key
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
执行的图示如下:
3. 排序算法的C实现
#include <stdio.h> #include <stdlib.h>#define SIZE 10int main(int argc, char const *argv[]){ int arry_int[SIZE]; int i ; int j ; int key; // initialize arry_int rand for ( i = 0; i < SIZE; i++ ) arry_int[i] = rand()%20; // print all elements before Insert sort for ( i = 0; i < SIZE; i++ ) printf("%d\t", arry_int[i] ); printf("\n"); // main loop for ( j = 1; j < SIZE; j++ ) { key = arry_int[j]; // compare with elements before j i = j - 1; while ( i >= 0 && arry_int[i] > key ) { // swap i and j elements arry_int[i+1] = arry_int[i]; i--; } arry_int[i+1] = key; } // print all elements after Insert sort for ( i = 0; i < SIZE; i++ ) printf("%d\t", arry_int[i] ); return 0;}
- 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
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
结果:
![]()
- ').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i
- 插入排序-【插入排序】
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 使用英特尔流式SIMD扩展优化动画模型的渲染流水线
- spring-ldap学习(二)
- 调用startActivityForResult,onActivityResult无响应的问题
- System.getProperty("catalina.home")+":"+System.getProperty("catalina.base")
- 上传本地项目到github
- 插入排序
- [ue4]摩尔纹(远处材质闪烁并有纹路)
- atof()和atoi()函数使用问题
- linux修改文件夹-文件目录权限
- MySQL开放3306端口不能访问的问题
- Hibernate入门
- android6.0修改控件选中的颜色深度
- 汇编语言 输出彩色字体
- 编程问题