快速排序
来源:互联网 发布:什么软件制作橙光立绘 编辑:程序博客网 时间:2024/04/30 22:13
#include "common.h"
//快速排序
template<class Elem>
void QuickSort(Elem arr[], int nStart, int nEnd,
Compare<Elem>& comp = Lower<Elem>())
{
if (nStart >= nEnd) return;
/* //优化:待排序元素个数小于10则使用插入排序
if (nEnd - nStart < 9)
{
return InsertSort(arr, nStart, nEnd, comp);
}
*/
int nLeft = nStart;
int nRight = nEnd;
int index = (nLeft + nRight) / 2; //选取分割点
swap(arr, index, nRight); //将分割点暂时放到末尾
index = nRight; //保存分割点位置
--nLeft;
//整理元素:小于分割点的放一端,其他另一端
while(nLeft < nRight)
{ //从首尾两端同时进行
while((++nLeft < nRight) && comp(arr[nLeft],arr[index]));
while((nLeft < --nRight) && comp(arr[index],arr[nRight]));
if (nLeft < nRight)
{
swap(arr, nLeft, nRight);
}
}
swap(arr, nLeft, index); //将分割点放置到两端的中间,即分界点
index = nLeft; //整理后的分割点位置
//子串排序
QuickSort(arr, nStart, index - 1, comp);
QuickSort(arr, index + 1, nEnd, comp);
}