qsort(char* a);//这个时候T就是char*了
" target="_blank">[glow=255,red,2]wfpb的部落格[/glow] 学习成为生活的重要组成部分!
写了个比较土的,怎么用template default function object给忘了,回头再写一个好点的。
#include <iostream>
#include <algorithm>
using namespace std;template<class T>
void quicksort(T* tStart, T* tEnd)
{
T* tPivot;if (tStart < tEnd)
{
tPivot = partition(tStart, tEnd);
quicksort(tStart, tPivot);
quicksort(tPivot+1, tEnd);
}
}template<class T>
T* partition(T* tStart, T* tEnd)
{
T tX = *tStart, *tLeft = tStart, *tRight = tEnd;
while (1)
{
while (!(*tRight < tX || tRight == tLeft))
tRight --;
while (*tLeft < tX && tLeft != tRight)
tLeft ++;if (tLeft < tRight)
swap(*tLeft, *tRight);
else
return tRight;
}
}struct str
{
public:
str(char *p) : p_str(p) {}
operator < (str s) {return strlen(p_str) < strlen(s.p_str);}
char * p_str;
};int main()
{
int intAr[] = {11,13,8,19,-21,32};
quicksort(&intAr[0], &intAr[5]);
for (int i = 0; i < 6; i++)
cout << intAr[i] << endl;float fAr[] = {11.2,14.1, -32.254,3.14159265,-2.182818281828,-2.182818281829,35.000};
quicksort(&fAr[0], &fAr[6]);
for (i = 0; i < 7; i++)
cout << fAr[i] << endl;str chr[] = {\"god\", \"dog\", \"good\" ,\"goods\", \"best\", \"dest\", \"bet\", \"beast\", \"cast\"};
quicksort<str>(&chr[0], &chr[8]);
for (i = 0; i < 9; i++)
cout << chr[i].p_str << endl;
return 0;
}