#include <iostream>
using namespace std;
template<class ElemType>
int partition(ElemType array[],int p,int q,int (*compare)(ElemType,ElemType))
{
int pos=p-1;
ElemType key=array[q],tmp;
for(int i=p;i<q;i++)
{
if(compare(array[i],key)){pos++;tmp=array[i];array[i]=array[pos];array[pos]=tmp;}
}
array[q]=array[pos+1];array[pos+1]=key;
return pos+1;
}
template<class ElemType>
void qsort(ElemType array[],int p,int q,int (*compare)(ElemType,ElemType))
{
if(p>=q)return;
int pos=partition<ElemType>(array,p,q,compare);
qsort(array,p,pos-1,compare);
qsort(array,pos+1,q,compare);
}
template<class Type>
int lessThan(Type e1,Type e2){return e1<=e2;}
int main(int argc,char *argv[])
{
int array[8]={3,2,1,8,9,5,2,1};
qsort(array,0,7,lessThan);
for(int i=0;i<8;i++){cout<<array[i]<<' ';}
cout<<endl;
}
C++实现快速排序算法,模板函数使用范例
最新推荐文章于 2025-09-08 16:00:16 发布
本文介绍了一个通用的快速排序算法模板实现,使用C++模板和函数指针来支持不同数据类型的排序,并通过一个整数数组的例子展示了如何调用该排序算法。
185

被折叠的 条评论
为什么被折叠?



