目录
1.算法原理
把第一个元素当成有序序列,然后把待排序序列的第一个值插入到有序序列中
下图蓝色方框里就是有序序列
2.分析过程和代码实现
2.1.排序趟数
由于是从第二个元素开始插入到有序序列,因此排序趟数为 n-1
2.2.每趟排序过程
每趟排序取待排序序列的第一个元素 ,从后向前依次与有序序列的值进行比较,若小于有序序列的值,则交换该两者的值,当有序序列的值小于该元素时,完成插入
例如排序数组 [5,2,3,4,1] 的过程如下图
按上述算法所编写的代码如下
void InsertSort(int t[],int n)
{
for(int i=1; i<n; i++)
{
for(int j=i-1; j>=0; j--)
{
if(t[j]>t[j+1])
{
int tem=t[j];
t[j]=t[j+1];
t[j+1]=tem;
}
}
}
}
3.改进与优化
把每次要插入的值先用临时变量保存下来,找到插入位置后直接插入即可
3.1.改进的方法
用临时变量 wait 保存要插入的值
在有序序列中,由后向前遍历,判断当前值是不是大于 wait ,若大于,则把当前值右移。
找到不大于 wait 的值后,把 wait 插入到该值后面
例如把 2 插入到有序序列 [1,3,4,5] 中的过程如下
按上述算法所编写的代码如下
void InsertSort2(int t[],int n)
{
int i,j,wait;
for(i=1; i<n; i++)
{
wait=t[i];
for(j=i; j>0&&t[j-1]>wait; j--)
{
t[j]=t[j-1];
}
t[j]=wait;
}
}
3.2.改进前后对比测试
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 20000
#define MAX 100000
int t[N];
int Ysort(int arr[],int n)//检测排序完成
{
int i=0;
int flg=89;//
while(i<n-1)
{
if(arr[i]>arr[i+1])
{
flg=78;
return flg;
}
i++;
}
return flg;
}
void InsertSort(int t[],int n)
{
for(int i=1; i<n; i++)
{
for(int j=i-1; j>=0; j--)
{
if(t[j]>t[j+1])
{
int tem=t[j];
t[j]=t[j+1];
t[j+1]=tem;
}
}
}
}
void InsertSort2(int t[],int n)
{
int i,j,wait;
for(i=1; i<n; i++)
{
wait=t[i];
for(j=i; j>0&&t[j-1]>wait; j--)
{
t[j]=t[j-1];
}
t[j]=wait;
}
}
int main()
{
int i;
int n=N;
int max=MAX;
printf("Size:%d\n",n);
printf("Max:%d\n",max);
for( i = 0; i < N; i++)
{
t[i] = rand()%MAX;
}
printf("%c \n",Ysort(t,n));
int begintime,endtime;
begintime=clock();
InsertSort(t,n);
endtime = clock();
printf("\n\nSort Running Time:%dms\n", endtime-begintime);
printf("This is InsertSort.\n");
printf("%c \n",Ysort(t,n));
for( i = 0; i < N; i++)
{
t[i] = rand()%MAX;
}
begintime=clock();
InsertSort2(t,n);
endtime = clock();
printf("\n\nSort Running Time:%dms\n", endtime-begintime);
printf("This is InsertSort2.\n");
printf("%c \n",Ysort(t,n));
return 0;
}
4.算法复杂度分析
空间复杂度:只用到一个临时变量,空间复杂度为 O(1)
时间复杂度:两层循环,时间复杂度为 O(n^2)