只是一个简短的说明,这不是家庭作业。我只是想重温我的算法。我在 C# 中使用 MergeSort,我编写了一个可以基于泛型进行排序的递归方法:
class SortAlgorithms
{
public T[] MergeSort<T> (T[] unsortedArray) where T : System.IComparable<T>
{
T[] left, right;
int middle = unsortedArray.Length / 2;
left = new T[middle];
right = new T[unsortedArray.Length - middle];
if (unsortedArray.Length <= 1)
return unsortedArray;
for (int i = 0; i < middle; i++)
{
left[i] = unsortedArray[i];
}
for (int i = middle; i < unsortedArray.Length; i++)
{
right[i - middle] = unsortedArray[i];
}
left = MergeSort(left);
right = MergeSort(right);
return Merge<T>(left, right);
}
private T[] Merge<T> (T[] left, T[] right) where T : System.IComparable<T>
{
T[] result = new T[left.Length + right.Length];
int currentElement = 0;
while (left.Length > 0 || right.Length > 0)
{
if (left.Length > 0 && right.Length > 0)
{
if (left[0].CompareTo(right[0]) < 0)
{
result[currentElement] = left[0];
left = left.Skip(1).ToArray();
currentElement++;
}
else
{
result[currentElement] = right[0];
right = right.Skip(1).ToArray();
currentElement++;
}
}
else if (left.Length > 0)
{
result[currentElement] = left[0];
left = left.Skip(1).ToArray();
currentElement++;
}
else if (right.Length > 0)
{
result[currentElement] = right[0];
right = right.Skip(1).ToArray();
currentElement++;
}
}
return result;
}
}
这行得通,但速度很慢。我已经使用 System.Diagnostic.StopWatch 来检查 Array.Sort(它使用 QuickSort 算法)的性能,以与我的 MergeSort 进行比较,并且差异如此之大,我想知道我是否实施了这个错误。任何意见?