哨兵排序算法

代码展示

复制代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 20
//直接排序
typedef struct
{
    int r[MAXSIZE + 1];
    int length;
} SqList;
int InsertSort(SqList* L)
{
    int i, j;
    for (i = 2; i <= L->length; i++)
    {
        if (L->r[i] < L->r[i - 1])
        {
            L->r[0] = L->r[i];//设置哨兵
            L->r[i] = L->r[i - 1];//交换位置
            for (j = i - 2; L->r[0] < L->r[j]; j--)
            {
                L->r[j + 1] = L->r[j];
            }
            L->r[j + 1] = L->r[0];
        }
        printf("第%d躺排序结果:", i-1);
        for (int k = 1; k <= L->length; k++)
        {
           /* if (k == L->length)
                printf("%d", L->r[k]);
            else*/
                printf("%d ", L->r[k]);
        }
        printf("\n");
    }
    return 1;
}
// 时间复杂度:O(n^2)  n为元素个数
int main()
{
    SqList L;

    int n;
    while (scanf("%d", &n) != -1)
    {
        L.length = n;

        for (int i = 1; i <= L.length; i++)
        {
            scanf("%d", &L.r[i]);
        }
        L.r[0] = -1;//数组下标为0的位置初始值为-1,设置为哨兵
        InsertSort(&L);
    }
      return 0;
}

运行结果与画图理解分析

第一行:输入数据的个数

第二行:从数组下标为1开始输入数据

数组下标为0的位置初始值为-1,设置为哨兵

相关推荐
Funny_AI_LAB41 分钟前
李飞飞联合杨立昆发表最新论文:超感知AI模型从视频中“看懂”并“预见”三维世界
人工智能·算法·语言模型·音视频
RTC老炮4 小时前
webrtc降噪-PriorSignalModelEstimator类源码分析与算法原理
算法·webrtc
深思慎考4 小时前
微服务即时通讯系统(服务端)——用户子服务实现逻辑全解析(4)
linux·c++·微服务·云原生·架构·通讯系统·大学生项目
草莓火锅6 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
j_xxx404_6 小时前
C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
开发语言·c++
散峰而望6 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
Kuo-Teng6 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie88896 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
曾几何时`7 小时前
C++——this指针
开发语言·c++
偷偷的卷7 小时前
【算法笔记 11】贪心策略六
笔记·算法