I'm trying to use a merge-sort algorithm to sort an Array of numbers, but the algorithm takes in a List<> not an Array[]
I've tried changing the algorithm to use an Array[] instead by replacing '.Count' with '.Length', but because of the fixed-size nature of Arrays I'm having trouble with the lines that use 'add' and 'remove'
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;
}
I would like to be able to pass an unsorted array into the method and it output a sorted array.
Arrays are fixed sized and do not share the same methods as Lists, which are variable sized. Thus you need to convert your Array to a List then pass the List as the param to the method. You can use:
List<object> list = myArray.Cast<Object>().ToList();
Or if you prefer linq:
List<object> list = myArray.ToList<object>();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments