/*
* 说明:经过本函数处理后,数组ItemArray[]中元素满足pRuleFunc(ItemArray[ItemR], ItemArray[ItemL])为True, 其中ItemR 〉ItemL;
*/
template T;
void QuickSort(ItemArray[], int ItemL, int ItemR, bool(*pRuleFunc(T, T))
{
if (ItemL >= ItemR)
{
return;
}
int iL = ItemL;
int iR = ItemR;
int ItemK = ItemArray[iL];
for ( ;iL < iR;)
{
// 从右向左寻找第一个使得pRuleFunc(ItemArray[iR], ItemK)为false的元素,并将其移动到ItemK的左侧
while((iL < iR) && pRuleFunc(ItemArray[iR], ItemK))
{
iR--;
}
ItemArray[iL] = ItemArray[iR];
// 从左向右寻找第一个使得pRuleFunc(ItemK, ItemArray[iL])为false的元素,并将其移动到ItemK的右侧
while((iL < iR) && pRuleFunc(ItemK,ItemArray[iL]))
{
iL++;
}
ItemArray[iR] = ItemArray[iL];
}
ItemArray[iL] = ItemK;
// 快速排序左侧,
QuickSort(ItemArray, ItemL, iL - 1, pRuleFunc);
// 快速排序右侧,
QuickSort(ItemArray, iL + 1, ItemR, pRuleFunc);
}
1。用例-数字排序
bool pIntCmp(int i, int j)
{
if (i < j)
{
return true;
}
else
{
return false;
}
}
int main(int argc, char* argv[])
{
int aTest[10] = {0, 1, 3, 4, 6, 9, 8, 7, 5, 2};
QuickSort<int>(aTest, 0, 9, pIntCmp);
return 0;
}
2。用例-字符串排序
bool pStrCmp(char *a, char*b)
{
if (NULL = a)
return false;
if (NULL == b)
return true;
if (strcmp(a, b) > 0)
return true;
else
return false;
}
int main(int argc, char* argv[])
{
char * bTest[10] = {"abcd", "hehe", "come on", "baby", "oh no", "haha", "how are you", "time out", "the second", "the first"};
QuickSort<char*>(bTest, 0, 9, pStrCmp);
return 0;
}