快排C++源码

快速排序:

分解:数组a[p..r]被划分为链两个(可能空)子数组a[p..q-1]和a[q+1..r],使得a[p..q-1]中的每个元素都小于等于a[q],而且,a[q]小于等于a[q+1,..r]中的元素。下表q的这个元素也在这个划分过程中进行计算。

解决:通过递归调用快速排序,对子数组a[p..q+1]和a[q+1..r]排序。

合并:因为两个子数组是就地排序的,将它们合并不需要操作,整个数组a[p..r]已排序。

/*************************************************************************/
/* this program just to show the QuickSort                               */
/* Author:SaoNian                                                        */
/* Time:2012/11/13                                                       */
/*************************************************************************/
#include <time.h>  
#include <stdlib.h>  
#include <iomanip.h>  

void quickSort(int *a,int start,int end);
int partition(int *a,int start,int end);
void showArray(int *a,int n);

int main()
{
	int n;
	cout<<"Please input the legnt of the Array:";
	cin>>n;
	srand((int)time(NULL));
	int * a=new int[n];
	for(int i=0;i<n;i++)
	{
		a[i]=rand()%n;
	}
	cout<<"the initial array:"<<endl;
	showArray(a,n);
	cout<<"now we sort it:"<<endl;
	quickSort(a,0,n-1);
	showArray(a,n);
	return 0;
}


void showArray(int *a,int n)
{
	for(int i=1;i<=n;i++)
	{
		cout<<setw(3)<<a[i-1];
		if(i%10==0)
		{
			cout<<endl;
		}
	}
}

int partition(int *a,int start,int end)
{
	int seed=a[start];//种子是start
	int j=start;
	int tmp;
	for(int i=(start+1);i<=end;i++)//一次划分找到start的位置
	{
		if(a[i]<=seed)
		{
			j=j+1;
			tmp=a[i];
			a[i]=a[j];
			a[j]=tmp;
		}
	}
	tmp=a[j];
	a[j]=a[start];
	a[start]=tmp;//交换最后一个比种子小和种子之间的位置
	return j;
}

void quickSort(int *a,int start,int end)
{
	if(start<end)
	{
		int pos=partition(a,start,end);
		quickSort(a,start,pos-1);
		quickSort(a,pos+1,end);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值