快速排序(c++)

2022/2/23 11:21:58

本文主要是介绍快速排序(c++),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

贴个代码在此
 

#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<windows.h>
#include<vector>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;

void QuickSort(vector<int>&v);
void QuickSort(vector<int>&,int L,int R);//将[L,R]区间划分
vector<int> Partition(vector<int>&,int,int);

void QuickSort(vector<int>&v)
{
	if(v.empty()||v.size()==1)return;
	QuickSort(v,0,v.size()-1);
	cout<<"end"<<endl;
}

void QuickSort(vector<int>&v,int L,int R)
{
	if(L>=R)return;
	srand((unsigned int)(time(NULL)));
	swap(v[R],v[rand()%(R-L+1)+L]);
	vector<int> p=Partition(v,L,R);
	cout<<"p[0] "<<p[0]<<" p[1] "<<p[1]<<endl;
	QuickSort(v,L,p[0]-1);
	QuickSort(v,p[1]+1,R);
}

vector<int> Partition(vector<int>&v,int L,int R)
{
//	if(L==R) return;
	int p=L-1,q=R;
	cout<<v[R]<<" v[R]"<<endl;
	
	while(L<q)
	{
		if(v[L]<v[R])
		swap(v[L++],v[++p]);
		else if(v[L]>v[R])
		swap(v[L],v[--q]);
		else L++;
	}
	swap(v[R],v[q]);
	return {p+1,q};
}

int main()
{
	vector<int>v;int temp;
		while(cin>>temp)
		{
	//		v.emplace(v.begin(),temp);
			v.push_back(temp);
			if(cin.get()=='\n')
			break;
		}
		QuickSort(v);
		for(auto it=v.begin();it!=v.end();it++)
		printf("%d ",*it);
	
}



这篇关于快速排序(c++)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程