栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【排序算法全解】之 - 插入排序(InsertSort)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【排序算法全解】之 - 插入排序(InsertSort)

目录

1.算法原理

2.分析过程和代码实现

2.1.排序趟数

2.2.每趟排序过程

3.改进与优化

3.1.改进的方法

3.2.改进前后对比测试

 4.算法复杂度分析


1.算法原理

把第一个元素当成有序序列,然后把待排序序列的第一个值插入到有序序列中

下图蓝色方框里就是有序序列

2.分析过程和代码实现

2.1.排序趟数

由于是从第二个元素开始插入到有序序列,因此排序趟数为  n-1

2.2.每趟排序过程

每趟排序取待排序序列的第一个元素 ,从后向前依次与有序序列的值进行比较,若小于有序序列的值,则交换该两者的值,当有序序列的值小于该元素时,完成插入

例如排序数组  [5,2,3,4,1] 的过程如下图

 按上述算法所编写的代码如下

void InsertSort(int t[],int n)
{
    for(int i=1; i=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; i0&&t[j-1]>wait; j--)
        {
            t[j]=t[j-1];
        }
        t[j]=wait;
    }
}

3.2.改进前后对比测试
#include 
#include
#include
#define   N 20000
#define MAX 100000
int t[N];
int Ysort(int arr[],int n)//检测排序完成 
{
	int i=0;
	int flg=89;//
	while(iarr[i+1])
		{
			flg=78;
			return flg;
		}
		i++;
	}
	return flg;
}
void InsertSort(int t[],int n)
{
	for(int i=1; i=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; i0&&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:%dn",n);
	printf("Max:%dn",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("nnSort Running Time:%dmsn", 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("nnSort Running Time:%dmsn", endtime-begintime);
	printf("This is InsertSort2.n"); 
	printf("%c  n",Ysort(t,n));
	return 0;
}

 4.算法复杂度分析

空间复杂度:只用到一个临时变量,空间复杂度为 O(1)

时间复杂度:两层循环,时间复杂度为 O(n^2)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号