/************************************************************************* > File Name: quicksort.cpp > Author:keson > Mail:[email protected] > Created Time: 2014年12月02日 星期二 10时34分01秒 ************************************************************************/ #include<iostream> #include<vector> #include<algorithm> #include<fstream> using namespace std; template <typename Comparable> void insertionSort( vector<Comparable> & a, int left, int right ) { for( int p = left + 1; p <= right; ++p ) { Comparable tmp = std::move( a[p] ); int j; for( j = p; j > left && tmp < a[j-1]; --j) a[j] = std::move( a[j-1]); a[j] = std::move( tmp ); } } template <typename Comparable> const Comparable &median3(vector<Comparable> &a,int left,int right) { int center=(left+right)/2; if(a[center]<a[left]) std::swap(a[left],a[center]); if(a[right]<a[left]) std::swap(a[left],a[right]); if(a[right]<a[center]) std::swap(a[center],a[right]); std::swap(a[center],a[right-1]); return a[right-1]; } template<typename Comparable> void quicksort(vector<Comparable> &a,int left,int right) { if(left+10<=right) { const Comparable &pivot=median3(a,left,right); //Begin partitioning int i=left,j=right-1; for(; ;) { while (a[++i]<pivot){} while (pivot<a[--j]){} if(i<j) std::swap(a[i],a[j]); else break; } std::swap(a[i],a[right-1]); quicksort(a,left,i-1); quicksort(a,i+1,right); } else insertionSort(a,left,right); } template<typename Comparable> void quicksort(vector<Comparable> &a) { quicksort(a,0,a.size()-1); } int main() { vector<int> vec; int val; ifstream in; ofstream out; in.open("NUMBER_FILE"); out.open("quick_sort"); while(in>>val) vec.push_back(val); cin.clear(); clock_t start_time=clock(); quicksort(vec); clock_t end_time=clock(); cout<<"Running time is:"<< static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC<<" S"<<endl; cout<<endl; for(auto c:vec) out<<c<<" "; cout<<endl; }