C语言——插入排序

先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。

#include <stdio.h>

#include <stdlib.h>

void insertion_sort(int *arr, int n)

{

for (int i = 1; i < n; i++)

{

int key = arri;

int j = i - 1;

while (j >= 0 && key < arrj)

{

arrj + 1 = arrj;

j--;

}

arrj + 1 = key;

}

}

void print_arry(int *arr,int n)

{

for (int i = 0; i < n; i++)

{

printf("%d ", arri);

}

}

int main()

{

int n;

scanf_s("%d", &n);

int *arr = (int *)malloc(sizeof(int) * n);

if (arr == NULL)

{

return 1;

}

else

{

for (int i=0; i < n; i++)

{

scanf_s("%d", arr + i);

}

insertion_sort(arr, n);

print_arry(arr, n);

}

free(arr);

return 0;

}

使用了malloc函数动态开辟内存空间,最后记得要释放。

自定义了两个函数模块,一个是插入排序函数,一个是打印函数

结果

相关推荐
luj_1768几秒前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法
Navigator_Z22 分钟前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
赵广陆31 分钟前
企业实战:Markdown图片检索
android·java·开发语言
C++、Java和Python的菜鸟32 分钟前
第3章 从0开始用若依
java·开发语言
wabs66633 分钟前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
LuminousCPP37 分钟前
数据结构基础篇(二):顺序表与链表全方位对比|从内存布局到 CPU 缓存理解底层差异
c语言·数据结构·经验分享·链表·缓存
夜雪一千1 小时前
Python 如何实现 SHA 加密?SHA1 / SHA256 / SHA512 实战教程
开发语言·python
有点。1 小时前
C++二叉树(一)
开发语言·数据结构·c++
民乐团扒谱机1 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
Nil2082 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵