(C++)数据结构排序---插入排序

插入排序基本思想:一个数组拥有n个数据,从第二个数据a[1]开始,与前面的数据a[0]比较,若a[1]<a[0],则a[1],a[0]互换位置,此时前两个数据为有序数据(由小到大);继续看第三个数据a[3],a[3]依次与前面的数据作比较,若a[3]<a[2],则二者互换位置,再与前一个数据比较,直到找到正确的位置。

需要进行(n-1)趟比较,第一趟进行一次比较,第n-1趟进行(n-1)次比较。

比较次数:(1+n-1)*(n-1)/2=n*(n-1)/2。需要一个辅助空间,用于交换数据。

平均情况的时间复杂度          最好情况的时间复杂度               最坏情况的时间复杂度         空间复杂度

         O(n^2)                                 O(n^2)                                        O(n^2)                      O(1)

代码实现1:

#ifndef _INSERTSORT_H
#define _INSERTSORT_H
#include<iostream>
using namespace std;

template<class Type>
void InsertSort(Type *a,int n)
{
	Type tem;
	for(int i=1;i<n;i++)
	{
		tem=a[i];
		while( i>0 && tem<a[i-1] )
		{
			a[i]=a[i-1];
			i--;
		}
		a[i]=tem;
	}
}
#endif 

代码实现2:

template <typename Type>
void InsertSort(Type a[],int n)
{
	for(int i=1;i<n;i++)
	{
		Type tem=a[i];
		int j;
		for(j=i-1;j>=0&&tem<a[j];j--)
		{
			a[j+1]=a[j];
		}
		a[j+1]=tem;
	 } 
}

因为待排序数据之前的数据为有序数据,故可以使用折半查找的方法找到数据的正确插入位置。

template<typename Type>
void BinInsertSort(Type a[],int n)
{
	for(int i=1;i<n;i++)
	{
		Type tem=a[i];
		int low=0,mid;
		int high=i-1;
		while(low<=high)
		{
			mid=(low+high)/2;
			if(tem<a[mid])
			high=mid-1;
			else
			low=mid+1;
		}
		for(int j=i-1;j>=low;j--)
		a[j+1]=a[j];
		a[low]=tem;
	}
 } 

测试代码:

#include<iostream>
#include"InsertSort.h"
using namespace std;
int main()
{
	int a[10]={18,23,15,3,8,54,12,54,76,100};
	for(int i=0;i<10;i++)
	cout<<a[i]<<" ";
	cout<<endl;
	InsertSort(a,10);
	for(int i=0;i<10;i++)
	cout<<a[i]<<" ";
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40951833/article/details/80757424