Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
SorterGenericArray
и SorterObjectArray
закрывающих фигурных скобок больше, чем открывающих. И бросается в глаза do
без while
.Сильно деградирует по скорости до O(n2) при неудачных выборах опорных элементов, что может случиться при неудачных входных данных. Этого можно избежать, выбирая опорный элемент случайно, а не фиксированным образом;
Не обязательно случайно, можно сделать быструю сортировку детерминировано за O(n log n).
template<class _RanIt,
class _Diff,
class _Pr> inline
void _Sort(_RanIt _First, _RanIt _Last, _Diff _Ideal, _Pr _Pred)
{ // order [_First, _Last), using _Pred
_Diff _Count;
for (; _ISORT_MAX < (_Count = _Last - _First) && 0 < _Ideal; )
{ // divide and conquer by quicksort
_STD pair<_RanIt, _RanIt> _Mid =
_Unguarded_partition(_First, _Last, _Pred);
_Ideal /= 2, _Ideal += _Ideal / 2; // allow 1.5 log2(N) divisions
if (_Mid.first - _First < _Last - _Mid.second)
{ // loop on second half
_Sort(_First, _Mid.first, _Ideal, _Pred);
_First = _Mid.second;
}
else
{ // loop on first half
_Sort(_Mid.second, _Last, _Ideal, _Pred);
_Last = _Mid.first;
}
}
if (_ISORT_MAX < _Count)
{ // heap sort if too many divisions
_STD make_heap(_First, _Last, _Pred);
_STD sort_heap(_First, _Last, _Pred);
}
else if (1 < _Count)
_Insertion_sort(_First, _Last, _Pred); // small
}
5000000:
MergeSort = 492.8ms
MergeSortInPlace = 670.9ms
MergeSortBottomUp = 536.2ms
QuickSort = 615.5ms
std::sort = 666.4ms
std::stable_sort = 628.6ms
10000000:
MergeSort = 1025.2ms
MergeSortInPlace = 1425.2ms
MergeSortBottomUp = 1117.6ms
QuickSort = 1269.2ms
std::sort = 1397.8ms
std::stable_sort = 1323.8ms
50000000:
MergeSort = 5318ms
MergeSortInPlace = 8034.67ms
MergeSortBottomUp = 6154ms
QuickSort = 7048ms
std::sort = 7671.33ms
std::stable_sort = 7189.33ms
100000000:
MergeSort = 11444ms
MergeSortInPlace = 17040ms
MergeSortBottomUp = 13166ms
QuickSort = 14647ms
std::sort = 15944ms
std::stable_sort = 14953ms
200000000:
MergeSort = 23447ms
MergeSortInPlace = 35907ms
MergeSortBottomUp = 27430ms
QuickSort = 30298ms
std::sort = 33544ms
std::stable_sort = 31094ms
могли бы управление алгоритмом вытащить наружу для тех кто понимает какой алгоритм в текущей задаче ему даст эти 10%
Я уверен что очень многие разработчики тут пишут приложения в которых есть обработка больших объемов данных и их пользователям пригодились бы те самые 10% производителности.
Писать код, от которого вас будет тошнить, потому как используется реализация, написанная на коленке?
array.Sort()
имеем array.SuperSort()
. Да даже если банальный статический метод в двух местах будет вызываться вместо Sort — что же, от этого тошнить должно? internal sealed class FunctorComparer<T> : IComparer<T> {
Comparison<T> comparison;
public FunctorComparer(Comparison<T> comparison) {
this.comparison = comparison;
}
public int Compare(T x, T y) {
return comparison(x, y);
}
}
[TestMethod]
public void TestComparerFull4()
{
Tuple<string, int> a = new Tuple<string, int>("1", 2), b = new Tuple<string, int>("2", 4);
Tuple<string, int> x = new Tuple<string, int>("2", 2), y = new Tuple<string, int>("2", 4);
var comparer = CustomComparer<Tuple<string, int>>.New(t => t.Item1).Add(t => t.Item2).CreateDelegate();
var comparerNeg = CustomComparer<Tuple<string, int>>.NewNeg(t => t.Item1).Add(t => -t.Item2).CreateDelegate();
Assert.AreEqual(-1, comparer(a, b));
Assert.AreEqual(1, comparer(b, a));
Assert.AreEqual(1, comparerNeg(x, y));
Assert.AreEqual(-1, comparerNeg(y, x));
}
internal void Sort(int left, int length)
{
#if FEATURE_CORECLR
// Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
// to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
// IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
IntrospectiveSort(left, length);
#else
if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
{
IntrospectiveSort(left, length);
}
else
{
DepthLimitedQuickSort(left, length + left - 1, IntrospectiveSortUtilities.QuickSortDepthThreshold);
}
#endif
}
Сортировка в .NET