1快排优化
template<class T, template <class>class Cmp = Great >
void FastSortPerfect(T *arr, size_t n, int first, int last)
{
assert(arr);
if (first < 0 || last >= n || first>last)
return;
int beg = first;
int end = last;
if (end - beg < 13)
{
InsertSort(arr + first, last - first+1);
return;
}
while (beg < end)
{
while (beg < end&&Cmp<T>()(arr[end], arr[beg]))
{
--end;
}
swap(arr[beg], arr[end]);
while (beg < end && (Cmp<T>()(arr[end], arr[beg])))
{
++beg;
}
swap(arr[beg], arr[end]);
}
//beg == end == 中间元素
FastSortPerfect(arr, n, first, beg - 1);
FastSortPerfect(arr, n, beg + 1, last);
}
2归并优化
//[)[)
template<class T,template<class>class Cmp = Great>
void MerGe(T * arr, int start, int cir, int end)
{
assert(arr);
int newLen = end - cir;
int * newArr = new int[newLen];
//保存后半部分值
for (int i = cir; i < end; ++i)
{
newArr[i-cir] = arr[i];
}
//将后半部分并入元数组
while (newLen&&cir-start)
{
//if (newArr[newLen - 1]>arr[cir - 1])
if (Cmp<T>()(newArr[newLen - 1], arr[cir - 1]))
{
arr[--end] = newArr[newLen - 1];
newLen--;
}
else
{
arr[--end] = arr[cir - 1];
cir--;
}
}
//如果后半部分有剩余,那么直接加入前半部分
//否则就不处理,因为本身就是在原数组中处理的
if (newLen)
{
for (int i = 0; i < newLen; ++i)
{
arr[start] = newArr[i];
}
}
delete[]newArr;
}
//②
template<class T, template<class> class Cmp = Great>
void MergeSort2(T array[],size_t n)
{
int step = 2;
while (step < n*2)
{
int start = 0;
while (start+step/2 <n)
{
int end = start + step;
if (end > n)
end = n;
MerGe<T>(array, start, start+step/2, end);
start = end;
}
step *= 2;
}
}
3时间空间复杂度对比