随机快速排序

#include<iostream>
#include<cstdlib>
using namespace std;
#define N 15


void printArray(int *a,int len)
{
	for(int i=0;i<len;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

void swap(int &a,int &b)
{
	int buf=a;
	a = b;
	b = buf;
	
}

void partition(int *a,int l,int r,int* ret)
{
	int less = l-1;
	int more = r+1;
	int p = l;
	int flag = a[r];
	while(p<more)
	{
		if(a[p] < flag)
		{
			swap(a[p],a[less+1]);
			less++;
			p++;
		}
		else if(a[p] > flag)
		{
			swap(a[p],a[more-1]);
			more--;
		}
		else
			p++;
	}
	ret[0] = less;
	ret[1] = more;
}

void quickSort(int *a,int l,int r)
{
	int ret[2]={0};
	if(l<r)
	{
		swap(a[r],a[l+rand()%(l-r)]);
		partition(a,l,r,ret);
		quickSort(a,l,ret[0]);
		quickSort(a,ret[1],r);
	}
}



int main()
{
	int a[N]={6,7,8,1,2,3,4,1,0,7,1,4,5,11,31};
	quickSort(a,0,N-1);
	printArray(a,N);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u014228447/article/details/80636457