算法--快速排序

本文深入探讨了快速排序算法的原理及实现细节,强调了选择中间元素作为边界的重要性,并介绍了如何通过改进减少栈空间的需求,提高排序效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速排序

快速排序的关键在于选取序列或者是文件的哪一个元素作为边界,理想情况下必须选择序列的中间元素。快速排序不适合对小型的序列进行排序。数目小的时候插入排序的效率高于快速排序。

快速排序是在所有同数量级(nlogn)的排序方法中,性能最好的。但是如uochushi记录序列按关键字有序或者基本有序时,快速排序将蜕化为冒泡排序,其时间复杂度为On2).而且在快速排序中需要一个栈的结构来存放每次递归的数据,在最坏的情况下,栈的最大深度为n.

若是改进快速排序,在一趟排序后比较分割所得两部分的长度。且先对长度段的子序列中的记录进行快速排序,则栈的最大深度可降为Ologn

思想:

建立一个分区,将比其大的元素置于前面,比其小的元素置于后面,得到一个位置,然后进行递归,继续进行分区分别的排序。


void FastSort(int *fastSortArray,int start,int end)
{
	if(start<end)
	{
		int potion=Parition(fastSortArray,start,end);
		cout<<"start: "<<start<<" end: "<<end<<endl;
		for(int index=0;index<10;index++)
		{
			cout<<*(fastSortArray+index)<<"  ";
		}
		cout<<endl<<endl;
		if(potion-start<=end-potion)
		{
			FastSort(fastSortArray,start,potion-1);
			FastSort(fastSortArray,potion+1,end);
		}
		else
		{
			FastSort(fastSortArray,start,potion-1);
		}
	}
}
int  Parition(int *fastSortArray,int start,int end)
{//关键在于临界值的处理
	int location=start;
	int compareData=*(fastSortArray+location);
	cout<<"比较数据是: "<<compareData<<endl;
	while(start<end)
	{
		while(*(fastSortArray+start+1)<compareData&&start<end)//从比较数据的后面一个开始进行比较
			start++;
		while(*(fastSortArray+end)>compareData&&start<end)
			end--;
		if (start<end)
		{
			int temp=*(fastSortArray+start+1);
		   *(fastSortArray+start+1)=*(fastSortArray+end);
		   *(fastSortArray+end)=temp;
		}		
	}
	if (start<=end)//当确定比较元素应该加入的位置时,交换值。
	{
		*(fastSortArray+location)=*(fastSortArray+start);
		*(fastSortArray+start)=compareData;
	}
	return (start);
}



小结:1、在进行快速排序或者是这种分治排序中最主要的是处理好临界值,index的问题。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值