今天,我们继续用模板写代码,不断加深模板的熟练程度,今天,我们一起来写一个快速排序,具体如例1所示:
例1 快速排序-数组
ArrayQuickSort.hpp内容:
#ifndef _ARRAY_QUICK_SORT_H_ #define _ARRAY_QUICK_SORT_H_ template<typename T> bool QuickSort(T * pInput, int nStart, int nEnd) { int nLow = nStart; int nHigh = nEnd; T tKey = pInput[nStart]; if (!pInput) return false; if (nStart >= nEnd) return true; while (nLow < nHigh) { while (nLow < nHigh && pInput[nHigh] > tKey) { nHigh--; } if (nLow >= nHigh) break; pInput[nLow] = pInput[nHigh]; nLow++; while (nLow < nHigh && pInput[nLow] <= tKey) { nLow++; } if (nLow >= nHigh) break; pInput[nHigh] = pInput[nLow]; nHigh--; } pInput[nLow] = tKey; return QuickSort<T>(pInput, nStart, nLow-1) && QuickSort<T>(pInput,nLow+1, nEnd); } #endifmain.cpp内容:
#include "ArrayQuickSort.hpp" #include <iostream> using namespace std; void main() { int i = 0; int a[10] = { 1,4,7,2,5,8,3,6,9,0 }; cout << "排序前:" << endl; for (i = 0; i < 10; i++) { cout << a[i] << ' '; } cout << endl; if (QuickSort<int>(a, 0, 10-1) == false) { cout << "排序失败." << endl; } else { cout << "排序后:" << endl; for (i = 0; i < 10; i++) { cout << a[i] << ' '; } } system("pause"); return; }运行效果如图1所示:
图1 运行效果
今天,我们共同完成了快速排序,希望大家回去多实践,熟练模板的使用。