第四步:上面几步基本上已经实现了模板库sort()函数的功能了,但是传入的参数好像不对,为此我们再做如下调整改变,同时将冒泡排序替换为快排.
?
?
//3).修改排序函数,使其符合sort(a, a+10),sort(a, a+10,cmp)模式,同时将冒泡改为快排
//系统的sort()函数有2种重载方式
//1.sort(迭代器1, 迭代器2);
//2.sort(迭代器1, 迭代器2, 谓词方法);
//说明:其实sort()函数所选择的排序方法是比较复杂的,包括(快排,堆排,插入排序).
//并且sort()会根据不同的数据而选择不同的排序方案,我们这里只以快排为例.
#include
using namespace std;
//比较函数
template
bool Max(T a, T b) { return a > b; } //函数模板(采用快速排序) template
void Qsort(T *begin, T *end, Func cmp) { T t = *begin; T *pL = begin, *pR = (end-1); if (pL >= pR) { return; } else { while (pL < pR) { while (cmp(t, *pR) && pL < pR) { --pR; } *pL = *pR; while (cmp(*pL, t) && pL < pR) { ++pL; } *pR = *pL; } *pL = t; } Qsort(pL+1,end,cmp); Qsort(begin,pR-1,cmp); } //重载函数模板,默认一种排序方案(小到大) template
void Qsort(T *begin, T *end) { T t = *begin; T *pL = begin, *pR = (end-1); if (pL >= pR) { return; } else { while (pL < pR) { while (t < *pR && pL < pR) { --pR; } *pL = *pR; while (*pL <= t && pL < pR) { ++pL; } *pR = *pL; } *pL = t; } Qsort(pL+1,end); Qsort(begin,pR-1); } int main(void) { int i, a[] = {17,82,37,89,42,76,67,15}; int len = sizeof(a)/sizeof(a[0]); // Qsort(a,a+len); Qsort(a,a+len,Max
); for (i = 0; i < len; ++i) { cout<
?