C++实现快速排序算法,模板函数使用范例

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值