算法导论之快速排序

   1:  /*
   2:  *Author:justinzhang
   3:  *Email:uestczhangchao@gmail.com
   4:  *Time:2011年5月11日15:58:40
   5:  *Discription:算法导论第7章,快速排序算法实现
   6:               change the previous c to cpp, and using template to make satisfy more data type
   7:               @Justin at:2012-9-4 21:57:52
   8:  */
   9:   
  10:  #include <iostream>
  11:  using namespace std;
  12:  /*交换两个数*/
  13:  template <typename T> void q_swap(T &x, T& y)
  14:  {
  15:      T tmp = x;
  16:      x = y;
  17:      y= tmp;
  18:  }
  19:   
  20:  /*以数组的最右边元素A[r]为主元对数组进行划分,返回pivot,pivot左边的元素都比A[r]小,右边的元素
  21:  *都比A[r]大;
  22:  */
  23:  template <typename T> int partition(T A[],int p, int r)
  24:  {
  25:      T x = A[r];
  26:      int i=p-1;
  27:      int j;
  28:      for(j=p;j<=r-1;j++)
  29:      {
  30:          if(A[j]<x)
  31:          {
  32:              i++;
  33:              q_swap<T>(A[i],A[j]);
  34:          }
  35:      }
  36:      i++;
  37:      q_swap(A[i],A[r]);
  38:      return i;
  39:  }
  40:   
  41:  /*利用partition不断的对数组进行划分,然后分别对划分后的两个部分进行排序(分治法思想)*/
  42:  template <typename T> void quicksort(T A[],int low, int high)
  43:  {
  44:      int pivot;
  45:      if(low<high)
  46:      {
  47:          pivot = partition<T>(A,low,high);
  48:          quicksort(A,low,pivot-1);
  49:          quicksort(A,pivot+1,high);
  50:      }
  51:   
  52:  }
  53:   
  54:  int main()
  55:  {
  56:      /*这里数组的下标从0开始*/
  57:      int A[]={55,5,4,6,7,8,-444,4};
  58:      int i;
  59:      quicksort<int>(A,0,7);
  60:      for(i=0;i<=7;i++)
  61:          cout << A[i] << endl;
  62:   
  63:      /*----test double qsort----------*/
  64:      cout << "test double quicksrot" << endl;
  65:      double data[] = {1.0, -2.0, 3.0,4.5};
  66:      quicksort<double>(data ,0, sizeof(data)/sizeof(double)-1);
  67:   
  68:      for(i=0;i<=sizeof(data)/sizeof(double)-1;i++)
  69:          cout << data[i] << endl;
  70:   
  71:      return 0;
  72:  }
  73:   
posted @ 2012-04-15 20:37  justinzhang  阅读(627)  评论(0编辑  收藏  举报