算法篇
作者:互联网
我是一个个人小开发,博客只供自己记录一些技能,以免忘记。勿喷
快速排序实现
1 #include <iostream> 2 #include <vector> 3 4 using namespace std; 5 6 7 void Quicksort(vector<int> &q,int l,int r) 8 { 9 if( l >= r) return; 10 int i = l - 1 , j = r + 1 , x = q[( l + r ) / 2] ; 11 while( i < j ) 12 { 13 do i++; while (q[i] < x); 14 do j--; while (q[j] > x); 15 if(i < j ) swap(q[i],q[j]); 16 } 17 Quicksort(q,l,j);Quicksort(q,j+1,r); 18 } 19 20 void Quicksort1(vector<int> &q,int l,int r) 21 { 22 if( l >= r) return; 23 int i = l - 1 , j = r + 1 , x = q.at(( l + r ) / 2) ; 24 while( i < j ) 25 { 26 do i++; while (q.at(i) < x); 27 do j--; while (q.at(j) > x); 28 if(i < j ) swap(q.at(i),q.at(j)); 29 } 30 Quicksort1(q,l,j);Quicksort1(q,j+1,r); 31 } 32 33 34 int main(int argc,char **argv) 35 { 36 //vector<int> p = {15,19,2,5,17,20,1,5,8,8,3,6,4}; 37 vector<int> p = {4,1,1,1,1,5,6}; 38 39 for(auto z : p ) cout << z << " , "; 40 cout << endl <<"======================|========================"<< endl; 41 42 43 vector<int> a(p); 44 Quicksort1(a,0,a.size() - 1 ); 45 for(auto z : a ) cout << z << " , "; 46 cout << endl <<"=============================================="<< endl; 47 48 return 0; 49 }
数据多的时候比冒泡快。所以理论上是快速排序快
还有vector使用[]重载的时候不检查越界,测试越过两个就会报错,不理解,还是用at好些
标签:do,int,Quicksort,while,算法,vector,Quicksort1 来源: https://www.cnblogs.com/jiafushunaixiaomeng/p/16434105.html