希尔排序,快速排序,堆排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cool_flag/article/details/78954201

最近在准备数据结构的考试,于是用博客记录下自己复习的过程。今天的内容是三种高级排序。
希尔排序
当序列增量为incr[k]=2(t-k+1)-1时,时间复杂度为O(n1.5)。以序列增量分组,对每组进行大小调整。

template<class T>
void ShellInsert(T elem[],int n,int incr)
{
	for(int i=incr;i<n;i++)
	{
		T e=elem[i];
		for(int j=i-incr;j>=0&&e<elem[j];j-=incr)
			elem[j+incr]=elem[j];
		elem[j+incr]=e;			
	}
}
template<class T>
void ShellSort(T elem[],int n,int incr[],int t)
{
	for(int k=0;k<t;k++)
		ShellInsert(elem,n,incr[k]);
}

快速排序
快速排序被公认为在所有同数量级O(nlogn)的排序算法中平均性能最好,但如果原序列有序时,快速排序将蜕化为起泡排序,时间复杂度为O(n^2).

template<class T>
int Patition(T elem[],int low,int high)
{//找到序列中一个数使得左边的数都比他小,右边的数都比他大。
	while(low<high)
	{
		while(low<high&&elem[low]<=elem[high])
			high--;
		Swap(elem[low],elem[high]);
		while(low<high&&elem[low]<=elem[high])
			low++;
		Swap(elem[low],elem[high]);
	}
	return low;
}
template<class T>
void QuickSortHelp(T elem[],int low,int high)
{//进行递归调整
	int pos=Partition(elem,low,high);
	QuickSortHelp(low,pos-1);
	QuickSortHelp(pos+1,high);
}
template<class T>
void QuickSort(T elem[],int n)
{
	QuickSortHelp(elem,0,n-1);
}

堆排序
最坏情况下时间复杂度为O(nlogn),只占用一个用于临时交换的临时存储空间

template<class T>
void SiftAdjust(int elem[],int high,int low)
{//elem中除elem[low]外均符合堆的定义,调整elem[low]使其成为大顶堆
	for(int f=low,i=2*f+1;i<=high;i=2*i+1)
	{	
		if(i<high&&elem[i]<elem[i+1])
			i++;
		if(elem[f]>=elem[i])
			break;
		Swap(elem[f],elem[i]);
		f=i;
	}
}
template<class T>
void HeapSort(int elem[],int n)
{//先将整个数组调整为大顶堆,再将最大的元素与最后一个元素交换,调整其成为大顶堆
	int i;
	for(i=(n-2)/2;i>=0;i--)
		SiftAdjust(i,n-1);
	for(i=n-1;i>=0;i--)
	{
		Swap(elem[0],elem[i]);
		SiftAdjust(0,i-1);
	}
}
		

猜你喜欢

转载自blog.csdn.net/cool_flag/article/details/78954201