快速排序算法实现及其测试代码

来源:互联网 发布:ubuntu mate 输入法 编辑:程序博客网 时间:2024/05/01 15:20
   写个快排来练下手,测试代码可以用来测试各种排序算法。快排的难点在于partition函数的实现,本文采用的是我觉得最容易理解故也最容易实现的两边夹算法(我自己命名的哈哈)。
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

template<class T>
int partition(T* a, int left, int right, int pivot)
{
    while (left< right)
    {
      while (a[left] <= pivot&& left <right)
      {
         ++left;
      }
      while (a[right] >= pivot&&  right> left)
      {
         --right;
           
      std::swap<T>(a[left],a[right]);      
    }
    // now left== right
    if (a[left]<= pivot)
    {
      return left;
    }
    else
    {
      return left-1;
     
}

template<class T>
void quickSort(T* a, int left, intright)    //right > left
{
    //以a[left]为pivot,在a[left+1]到a[right]之间找到其插入位置,此位置及其左边元素都小于等于pivot,右边元素则大于等于pivot
    int pos =partition<T>(a, left+1, right,a[left]);
    //将pivot插入正确位置,此操作后pos左侧数组元素均小于等于a[pos],右侧数组元素均大于等于a[pos]
   std::swap(a[left], a[pos]);
    // 递归
    if(pos  > left+1)
    {
      quickSort<T>(a,left, pos-1);      
    }
    if (right> pos+1)
    {
      quickSort<T>(a,pos+1, right);
    }
}

template<class T>
void sort(T* a, int len)
{
    if (len> 1)
    {
      quickSort<T>(a, 0,len-1);
    }
}

#define SIZE 100
#define TEST_TIMES 1000000

int main()
{
   srand((unsigned)time(NULL));
    inta[SIZE];
    for (inttimes = 0; times < TEST_TIMES; ++ times)
    {
      for (int i = 0; i < SIZE;++i)
      {
         a[i] = rand() % SIZE;
      }
      sort(a, SIZE);
      for (int i = 0; i < SIZE-1;++i)
      {
         if (a[i] > a[i+1])
         {
            cerr << "algorithmfailed" << endl;
            for (int j = 0; j < SIZE-1;++j)
            {
               cerr << a[j]<< ",";
            }
            cerr << a[SIZE-1]<< endl;
            return 1;
         }
      }
    }
    return0;
}

0 0
原创粉丝点击