现在的位置: 首页 > 综合 > 正文

C++实现快速排序

2018年03月20日 ⁄ 综合 ⁄ 共 633字 ⁄ 字号 评论关闭

#include<iostream>
#include<vector>
using namespace std;
/*
*快速排序算法平均时间复杂度为O(nlog(n)),最坏情况O(n^2)
*/
template <class T>
void swap(const T &m,const T &n){
T temp;
temp=m;
m=n;
n=temp;
}
int part(vector<int> &Sort,int a,int b){
int temp=Sort[a];
while(a<b){//此处注意陷入死循环
while(a<b&&Sort[b]>=temp)b--;
swap(Sort[a],Sort[b]);
while(a<b&&Sort[a]<=temp)a++;
swap(Sort[a],Sort[b]);
}
return a;
}
void quick_sort(vector<int> &Sort,int a,int b){
if(a<b){
int mid=part(Sort,a,b);
quick_sort(Sort,a,mid-1);
quick_sort(Sort,mid+1,b);
}
}
int main(int argc,char *argv[]){
int n,i;
cin>>n;
vector<int> Sort(n);
for(i=0;i<n;i++){
cin>>Sort[i];
}
quick_sort(Sort,0,n-1);
for(i=0;i<n;i++){
cout<<Sort[i]<<" ";
}
return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.