
快速排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <iostream> #include <algorithm> #include <ctime> using namespace std; class quick_sort { public: typedef int T; explicit quick_sort(T* src, int beg, int end); private: void sub_sort(int beg, int end); T* m_src; }; quick_sort::quick_sort(quick_sort::T *src, int beg, int end):m_src(src) { srand(time(0)); sub_sort(beg, end); } void quick_sort::sub_sort(int beg, int end) { int i = beg - 1, j = end; if(end <= beg) return; T piv = m_src[rand()%(end-beg) + beg]; for( ; ; ) { while(m_src[++i] < piv); while(piv < m_src[--j]); if ( i >= j) break; swap(m_src[i], m_src[j]); } sub_sort(beg, i); sub_sort(i+1, end); } int main() { const int n = 20; int src[n]; for(int i = 0; i < n; ++i) { src[i] = n - i; } quick_sort(src, 0, n); for(int i = 0; i < n; ++i) { cout<<src[i]<<endl; } //system("pause"); return 0; } |
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Be the first to comment on this entry.