1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#ifndef QUICKSORTS_H
#define QUICKSORTS_H
using namespace std;
template <class T>
void quickSort(vector<T>& set, bool (*compare)(const T&, const T&))
{
quickSort(set, 0, set.size()-1, compare);
}
template <class T>
void quickSorts(vector<T>& set, int start, int end, bool (*compare)(const T&, const T&))
{
int pivotPoint;
if (start < end)
{
pivotPoint = partition(set, start, end, compare); // Get the pivot point
quickSort(set, start, pivotPoint - 1, compare); // Sort first sublist
quickSort(set, pivotPoint + 1, end, compare); // Sort second sublist
}
}
template <class T>
int partition(vector<T>& set, int start, int end, bool (*compare)(const T&, const T&))
{
int pivotIndex;
int mid;
T pivotValue;
mid = (start + end) / 2;
swap (set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
for (int scan = start + 1; scan <= end; scan++)
{
if (compare(set[scan], pivotValue))
{
pivotIndex++;
swap (set[pivotIndex], set[scan]);
}
}
swap(set[start], set[pivotIndex]);
return pivotIndex;
}
#endif
|