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 2022-04-13 14:14  低头捡石頭  阅读(50)  评论(0)    收藏  举报

导航