快速排序

复制代码
  1 #include <iostream>
  2 #include <vector>
  3 using namespace std;
  4 template <typename Comparable>
  5 void quicksort( vector<Comparable> & a)
  6 {
  7     quicksort(a,0,a.size()-1);
  8 }
  9 template <typename Comparable>
 10 const Comparable & median3(vector<Comparable> & a,int left,int right)
 11 {
 12     int center = (left + right)/2;
 13     if(a[center] < a[left])
 14         swap(a[left],a[center]);
 15     if(a[right] < a[left])
 16         swap(a[left],a[right]);
 17     if(a[right] < a[center])
 18         swap(a[center],a[right]);
 19 
 20     swap(a[center],a[right - 1]);
 21     return a[right-1];
 22 }
 23 template <typename Comparable>
 24 void quicksort( vector<Comparable> & a,int left,int right)
 25 {
 26     if(left + 10 <= right)
 27     {
 28         Comparable pivot = median3(a,left,right);
 29 
 30         int i=left,j=right-1;
 31         for( ; ; )
 32         {
 33             while(a[++i] < pivot){}
 34             while(pivot < a[--j]){}
 35             if(i<j)
 36                 swap(a[i],a[j]);
 37             else
 38                 break;
 39         }
 40         swap(a[i],a[right-1]);
 41         quicksort(a,left,i-1);
 42         quicksort(a,i+1,right);
 43     }
 44     else
 45         insertionSort(a,left,right);
 46 }
 47 /*template <typename Comparable>
 48 void insertionSort(vector<Comparable> & a)
 49 {
 50     int j;
 51     for(int p = 1;p<a.size();p++)
 52     {
 53         Comparable tmp=a[p];
 54         for(j=p;j>0 && tmp<a[j-1];j--)
 55             a[j]=a[j-1];
 56         a[j]=tmp;
 57     }
 58 }
 59 template <typename Iterator,typename Comparator>
 60 void insertionSort(const Iterator & begin,const Iterator & end,Comparator lessThan)
 61 {
 62     if(begin != end)
 63         insertionSort(begin,end,lessThan,*begin);
 64 }
 65 template <typename Iterator,typename Comparator,typename Object>
 66 void insertionSort(const Iterator & begin, const Iterator & end , Comparator lessThan,const Object & obj)
 67 {
 68     Iterator j;
 69     for(Iterator p =begin+1;p != end;++p)
 70     {
 71         Object tmp = *p;
 72         for(j=p; j!=begin && lessThan(tmp,*(j-1)); --j)
 73             *j = *(j-1);
 74         *j = tmp;
 75     }
 76 }*/
 77 int main()
 78 {
 79     vector<int> ivec;
 80     ivec.push_back(1);
 81     ivec.push_back(9);
 82     ivec.push_back(2);
 83     ivec.push_back(10);
 84     ivec.push_back(3);
 85     ivec.push_back(11);
 86     ivec.push_back(4);
 87     ivec.push_back(12);
 88     ivec.push_back(5);
 89     ivec.push_back(13);
 90     ivec.push_back(6);
 91     ivec.push_back(14);
 92     ivec.push_back(7);
 93     ivec.push_back(15);
 94     ivec.push_back(8);
 95     ivec.push_back(16);
 96     quicksort(ivec);
 97     for(int j = 0;j<ivec.size();j++)
 98         cout<<ivec[j]<<endl;
 99     return 0;
100 } 
复制代码
posted @ 2017-05-19 21:56  罗志均  阅读(133)  评论(0编辑  收藏  举报
友情链接:回力 | 中老年女装 | 武汉英语培训机构 | 留学费用一览表 | 托福考试费用