58 lines
1.4 KiB
C++
58 lines
1.4 KiB
C++
/* -----------------------------------------------------------------------------
|
|
GSFramework
|
|
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
|
|
----------------------------------------------------------------------------- */
|
|
|
|
|
|
#ifndef __CONTAINER_SORT__
|
|
#define __CONTAINER_SORT__
|
|
|
|
|
|
namespace GS {
|
|
|
|
class ContainerSort
|
|
{
|
|
template <typename T, typename L> static inline void Swap(L &t, int i, int j)
|
|
{
|
|
if (i != j)
|
|
{ T swap = t[j]; t[j] = t[i]; t[i] = swap; }
|
|
}
|
|
template <typename T, typename L, typename C> static int QuickSortPartition(L &t, C compare, int first, int last, int pivot)
|
|
{
|
|
Swap <T, L> (t, pivot, last);
|
|
|
|
int j = first;
|
|
for (int i = first; i < last; ++i)
|
|
if (compare(t[i], t[last]) > 0)
|
|
{
|
|
Swap <T, L> (t, i, j);
|
|
++j;
|
|
}
|
|
|
|
Swap <T, L> (t, j, last);
|
|
return j;
|
|
}
|
|
template <typename T, typename L, typename C> static void QuickSortStep(L &t, C compare, int first, int last)
|
|
{
|
|
if (first < last)
|
|
{
|
|
int pivot = (first + last) / 2;
|
|
pivot = QuickSortPartition <T, L, C> (t, compare, first, last, pivot);
|
|
|
|
QuickSortStep <T, L, C> (t, compare, first, pivot - 1);
|
|
QuickSortStep <T, L, C> (t, compare, pivot + 1, last);
|
|
}
|
|
}
|
|
|
|
public:
|
|
|
|
/// Quick-sort a container in-place.
|
|
template <typename T, typename L, typename C> static void QuickSort(L &t, C compare)
|
|
{ QuickSortStep <T, L, C> (t, compare, 0, t.GetCount() - 1); }
|
|
};
|
|
|
|
} // GS
|
|
|
|
|
|
#endif // __CONTAINER_SORT__
|