快速排序(递归)

快速排序(递归)

//因为最近时间问题,该博客待完善
快速排序,时间复杂度:理想的情况是,每次划分所选择的中间数恰好将当前序列几乎等分,经过log2n趟划分(一次划分算法从两头交替搜索,直到low和hight重合,因此一次划分算法的时间复杂度是O(n);),整个算法的时间复杂度为O(nlog2n)。最坏情况:O(n2)。
快速排序很好理解,不过源码写起来如果不参考书籍的话可能需要耗费一定时间去思考,我就没有参考书籍.下面就是我用递归写的快速排序,仅供参考.

#include <iostream>
#include <time.h>
#include <stdlib.h>
/*
*输入随机数列元素个数,自动生成并排序
*/
using namespace std;

int speedSort(int* p,int *low,int* high);

int main()
{
	srand(time(NULL));

	int length = 0;
	cout << "Please enter array's length"<<endl;
	cin >> length;
	int* a = new int[length];
	cout << "Please enter the elements"<<endl;
	for (int i = 0; i < length; i++)
		a [i]=rand()%(length+1);

	speedSort(a,&a[0],&a[length-1]);
	for (int i = 0; i < length; i++)
		cout << a[i] << ' ';
	return 0;
}

int speedSort(int* p,int *low,int *high)
{
	int m;
	int* y1 = low, * y2 = high;
	while (low < high)
	{
		if (*low <= *high)
			high--;
		else
		{
			m = *low;
			*low = *high;
			*high = m;
			low++;
			while(low < high && *low <= *high)
				low++;
			if(low < high && *low > *high)
			{
				m = *low;
				*low = *high;
				*high = m;
				high--;
			}
		}
	}
	if (y1 < low - 1)
		speedSort(p, y1, low - 1);
	if (y2 > low + 1)
		speedSort(p, low + 1, y2);
	return 0;
}

你的赞就是我不托更的动力(●’◡’●)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值