C++ 快速排序代码

自己写的C++快速排序代码

//Quick排序

class Quick_Sort
{
public:
     Quick_Sort();
     ~Quick_Sort();

public:
     template <class T>
     static int  Partition(T *arry, const int start, const int finish);
     template <class T>
     static void QuickSort(T *arry, const int start, const int finish);
     template <class T>
     static void swap (T* _target, T* _source, const unsigned size);
};

Quick_Sort::Quick_Sort()
{
}

Quick_Sort::~Quick_Sort()
{
}

//对数组进行划分

template <class T>
int Quick_Sort::Partition(T *arry, const int start, const int finish)
{
     unsigned TSize = sizeof(T);

     int i = start - 1;
     T key = arry[finish];

     for (int j = start; j < finish; j++)
     {
          if (arry[j] <= key)
          {
              i++;
              swap(arry + i, arry + j, TSize);
          }
     }
     swap(arry + i + 1, arry + finish, TSize);

     return i + 1;
}

 

//快排

template <class T>
void Quick_Sort::QuickSort(T *arry, const int start, const int finish)
{
     if (start < finish)
     {
          unsigned pivot = Partition(arry, start, finish);
          QuickSort(arry, start, pivot - 1);
          QuickSort(arry, pivot + 1, finish);
     }
}

//交换值

template <class T>
void Quick_Sort::swap (T* _target, T* _source, const unsigned size)
{
     if (sizeof(T) < 128)
     {
          T temp;

          temp = *_target;
          *_target = *_source;
          *_source = temp;
     }
     else
     {
          T* _temp = 0;

           try
          {
                _temp = (T*)::operator new (size);
           }
           catch (bad_alloc& baRef)
           {
                 cerr << "Error in Swap function: Can't allocate memory: " << baRef.what() << endl;
                 throw;
           } 

          memcpy (_temp, _target, size);
          memcpy (_target, _source, size);
          memcpy (_source, _temp, size);

         ::operator delete (_temp);
         _temp = 0;
     }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值