利用直接插入排序进行将数组序列从小到大排序

1 题目

功能:直接插入排序
描述:利用直接插入排序进行将数组序列从小到大排序

2 思路

原始顺序: 34, 12, 45, 3, 8, 23, 89, 52, 24, 10

在代码中将数组 a[0] 置为监视哨

趟数 监视哨 排序结果
1 34 (12,) 34, 45, 3, 8, 23, 89, 52, 24, 10
2 12 (12, 34,) 45, 3, 8, 23, 89, 52, 24, 10
3 45 (12, 34, 45,) 3, 8, 23, 89, 52, 24, 10
4 3 (3, 12, 34, 45,) 8, 23, 89, 52, 24, 10
5 8 (3, 8, 12, 34, 45,) 23, 89, 52, 24, 10
6 23 (3, 8, 12, 23, 34, 45,) 89, 52, 24, 10
7 89 (3, 8, 12, 23, 34, 45, 89,) 52, 24, 10
8 52 (3, 8, 12, 23, 34, 45, 52, 89,) 24, 10
9 24 (3, 8, 12, 23, 24, 34, 45, 52, 89,) 10
10 10 (3, 8, 10, 12, 23, 24, 34, 45, 52, 89,)

以上是整个的插入排序算法的过程

3 代码

#include <stdio.h> 
#include <stdlib.h>

/**
功能:直接插入排序
描述:利用直接插入排序进行将数组序列从小到大排序
**/

void insort(int s[], int n)	{					// 自定义函数isort

    int i, j;
    for (i = 2; i <= n; i++) {					// 数组下标从2开始,0 位置做监视哨,1位置一个数据无可比性
        s[0] = s[i];							// 给监视哨赋值
        j = i - 1;								// 确定要进行比较的元素的最右边位置
        while (s[0] < s[j]) {
            s[j + 1] = s[j];					// 数据右移
            j--;								// 移向左边一个未比较的数
        }
        s[j + 1] = s[0];						// 在确定的位置插入s[i]
    }
}

int main(int argc, char const *argv[]) { 
    int a[11], i;									// 定义数组及变量为基本整型
    printf("请输入10个数据:\n");
    for (i = 1; i <= 10; i++)
        scanf("%d", &a[i]);							// 接收从键盘中输入的10个数据到数组a中
    printf("原始顺序:\n");
    for (i = 1; i < 11; i++)
        printf("%3d", a[i]);						// 将未排序前的顺序输出
    insort(a, 10);									// 调用自定义函数isort()
    printf("\n插入数据排序后顺序:\n");
    for (i = 1; i < 11; i++)
        printf("%3d", a[i]);						// 将排序后的数组输出
    printf("\n");
}

示例结果:

$ gcc ex058.c -o demo
$ ./demo
请输入10个数据:
34
12
45
3
8
23
89
52
24
10
原始顺序:
 34 12 45  3  8 23 89 52 24 10
插入数据排序后顺序:
  3  8 10 12 23 24 34 45 52 89
posted @   哈哈哈py_easy  阅读(232)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
点击右上角即可分享
微信分享提示