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 = arr[i];

int j = i - 1;

while (j >= 0 && key < arr[j])

{

arr[j + 1] = arr[j];

j--;

}

arr[j + 1] = key;

}

}

void print_arry(int *arr,int n)

{

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

{

printf("%d ", arr[i]);

}

}

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函数动态开辟内存空间,最后记得要释放。

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

结果

相关推荐
喜欢吃燃面13 小时前
算法竞赛中的堆
c++·学习·算法
资深web全栈开发13 小时前
LeetCode 1590:使数组和能被 p 整除(前缀和 + 哈希表优化)
算法·leetcode·前缀和·算法优化·哈希表·go 语言·取模运算
CoderYanger13 小时前
递归、搜索与回溯-综合练习:27.黄金矿工
java·算法·leetcode·深度优先·1024程序员节
zs宝来了13 小时前
HOT100系列-堆类型题
数据结构·算法·排序算法
报错小能手13 小时前
数据结构 带头节点的链表
数据结构·链表
大吱佬13 小时前
GO 八股整理(自用)
开发语言·后端·golang
froginwe1113 小时前
Go 语言结构体
开发语言
Christo313 小时前
ICML-2019《Optimal Transport for structured data with application on graphs》
人工智能·算法·机器学习·数据挖掘
sin_hielo13 小时前
leetcode 1590
数据结构·算法·leetcode
吃着火锅x唱着歌14 小时前
LeetCode 2748.美丽下标对的数目
数据结构·算法·leetcode