#include<stdio.h>
#include<time.h>
/*
效率高的情况:
1. 数据基本有序
2. 元素个数小
*/
#define MAX 10
void Insert_sort(int a[], int length)
{
for (int i = 1; i < length; i++)
{
int j;
if (a[i] < a[i-1])
{
int temp = a[i];
for (j = i-1; j>=0 && a[j] > temp; j--)
{
a[j+1] = a[j];
}
a[j+1] = temp;
}
}
}
void Show(int a[])
{
for (int i = 0; i < MAX; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int a[MAX];
srand((unsigned int)time(NULL));
for (int i = 0; i < MAX; i++)
{
a[i] = rand() % MAX;
}
Show(a);
Insert_sort(a, MAX);
Show(a);
return 0;
}
数据结构-排序算法之插入排序(C语言实现)
最新推荐文章于 2022-09-01 00:13:26 发布