C笔记 - 算法:插入排序

插入排序

1 - 插入排序(Insertion-Sort)是通过构建有序序列,对未排序数据在已排序序列中从后向前扫描,找到相应位置并插入(现实生活中和朋友们打扑克时,回一下如何整理顺子的,是的,就是插入排序)

3 - 代码示例 

复制代码
 1 #include <stdio.h>
 2 void improvedBubbleSort(void);
 3 int main(int argc, const char * argv[]) {
 4      
 5      
 6      int array[] = {12,91,21,10,13,88,66};
 7      int lenth = 7;
 8      
 9      // 将要排序的元素
10      int currentNumber = 0;
11      // 将要排序元素的前一个元素的索引
12      int preIndex = 0;
13      
14      // 索引从 1 开始,方便理解
15      for (int i = 1; i < lenth; i ++) {
16           
17           preIndex = i - 1;
18           currentNumber = array[i];
19           
20           //升序:如果前一个元素比需要排列的元素大,那么就把 currentNumber 不断的向前移动
21           while (preIndex >=0 && array[preIndex] > currentNumber) {
22                
23                array[preIndex+1] = array[preIndex];
24                preIndex--;
25           }
26           
27           // 注意插入的索引是 [preIndex + 1]
28           array[preIndex + 1] = currentNumber;
29           
30           printf("-------第 %d 轮排序------\n\n",i);
31           for (int i = 0; i < lenth -1; i ++) {
32                 printf("%d  ",array[i]);
33           }
34           printf("\n\n");
35           
36           // 最终换行
37           if (lenth == 6) {
38 
39                printf("\n\n");
40           }
41      }
42      
43      return 0;
44 }
复制代码

日志信息

 

posted on   低头捡石頭  阅读(45)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2018-04-13 UI基础 - UIBezierPath:FillMode
2018-04-13 UI基础 - UIBezierPath:反转路径 | 虚线
2018-04-13 UI基础 - UIBezierPath 常用API
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示