快速排序摸板,用C++实现

来源:互联网 发布:游戏编程精粹 pdf 编辑:程序博客网 时间:2024/05/17 23:09
0
推荐

#i nclude "iostream"
#i nclude "vector"
#i nclude "fstream"
using namespace std;
const int MAX=100;

//快速排序类模板
template<class elemType>
class quick_sort{
 public:
  int partition(int low,int high);
  void recquick_sort(int frist,int last);
  quick_sort(vector<elemType>& s);
  ~quick_sort();
 protected:
  vector<elemType> l;
};

template<class elemType>
quick_sort<elemType>::quick_sort(vector<elemType>& s)
{
 l=s;
 recquick_sort(0,l.size()-1);
 for(vector<int>::iterator iter=l.begin();iter!=l.end();iter++)
   cout<<*iter<<" ";
  cout<<endl;
}
template<class elemType>
quick_sort<elemType>::~quick_sort(){
}
template<class elemType>
void quick_sort<elemType>::recquick_sort(int first,int last)
{
 int poiv;
 if(first<last)
 {
  poiv=partition(first,last);
  recquick_sort(first,poiv-1);
  recquick_sort(poiv+1,last);
 }
}
template<class elemType>
int quick_sort<elemType>::partition(int low,int high)
{
 elemType poiv;
 poiv=l[low];
 while(low<high)
 {
  while(low<high&&l[high]>=poiv) --high;
  l[low]=l[high];
  while(low<high&&l[low]<=poiv) ++low;
  l[high]=l[low];
 }
 l[low]=poiv;
 return low;
}
int main()
{
 int i,n,e;
 vector<int> l;
 ifstream in;
 in.open("in.txt");
 if(!in)
 {
  cerr<<"error: unable to open the file:"<<in<<endl;
  return -1;
 }
 while(in>>n)
 {
  for(i=0;i<n;i++)
  {
   in>>e;
   l.push_back(e);
  }
  quick_sort<int> q(l);
  l.resize(0);
 }
 return 0;
}


原创粉丝点击