哨兵排序算法

代码展示

复制代码
#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,设置为哨兵

相关推荐
aqiu11111115 分钟前
【C++算法打怪专栏】8. 字符串转换整数 (atoi)
开发语言·c++·算法
h39745 小时前
DirectShow过滤器开发-视频源过滤器
c++·windows·音视频·directshow
程序猿编码7 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
西飘客7 小时前
vs 怎么根据dll 生成lib文件
c++·qt
程序员老陆8 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
信奥卷王9 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵9 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG10 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z11 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode