直接插入排序就是在已排序的有序序列里插入一个新的记录仍然有序,其插入位置的确定就是将带插入的记录与有序中的记录依次比较找到合适位置并插入。
时间复杂度:n的平方
算法实现:
设置监视哨主要是防止数据后移时丢失
<span style="font-size:18px;">void InsertSort(int a[], int n) {
int i, j;
for (i = 2; i <= n; i++) {//数组下标从2开始,a[0]作为监视哨,a[1]一个数据无可比性
a[0] = a[i]; //给监视哨赋值
j = i - 1; //比较的元素
while (a[0]<a[j])
{
a[j + 1] = a[j];//数据右移
j--;
}
a[j + 1] = a[0]; //在确定位置插入新的数
}
}</span>
主函数:(注意:数组元素从下标1开始)
<span style="font-size:18px;">#include<stdio.h>
#define N 100
void InsertSort(int a[], int n);
main() {
int n, i, t;
int a[N];
printf("请输入你要排序的数组元素个数:");
scanf_s("%d", &n);
printf("请输入你要排序的数组元素:");
for (i = 1; i <=n; i++) {
scanf_s("%d", &a[i]);
}
InsertSort(a, n);
for (t = 1; t <= n; t++) {
printf("%5d", a[t]);
}
printf("\n");
getch();
}</span>