我正在尝试使用合并排序算法对数字数组进行排序,但该算法接受 List<> 而不是 Array[]
我尝试更改算法以使用 Array[],而不是将 '.Count' 替换为 '.Length',但由于数组的固定大小性质,我在使用 'add' 和'消除'
private static List<int> MergeSort(List<int> unsorted)
{
if (unsorted.Count <= 1)
return unsorted;
List<int> left = new List<int>();
List<int> right = new List<int>();
int middle = unsorted.Count / 2;
for (int i = 0; i < middle; i++)
{
left.Add(unsorted[i]);
}
for (int i = middle; i < unsorted.Count; i++)
{
right.Add(unsorted[i]);
}
left = MergeSort(left);
right = MergeSort(right);
return Merge(left, right);
}
private static List<int> Merge(List<int> left, List<int> right)
{
List<int> result = new List<int>();
while (left.Count > 0 || right.Count > 0)
{
if (left.Count > 0 && right.Count > 0)
{
if (left.First() <= right.First())
{
result.Add(left.First());
left.Remove(left.First());
}
else
{
result.Add(right.First());
right.Remove(right.First());
}
}
else if (left.Count > 0)
{
result.Add(left.First());
left.Remove(left.First());
}
else if (right.Count > 0)
{
result.Add(right.First());
right.Remove(right.First());
}
}
return result;
}
我希望能够将未排序的数组传递到该方法中,并输出一个已排序的数组。
慕尼黑5688855
相关分类