I am learning to code and I though I’d try writing a merge sort algorithm (something we heard about in our analytic course but NOT homework). I was working from the pseudo code the trainer showed us but I cannot identify the problem. Any chance someone could point me in the right direction?
edit: The algorithm only returns the first value in the List.
static List<int> mergeSort(List<int> mj)
{
List<int>m = mj;
if(m.Count <= 1)
return m;
List<int> merge = new List<int>();
List<int> left = new List<int>();
List<int> right = new List<int>();
int middle = m.Count/2;
for (int i = 0; i < middle; i++)
left.Add(m[i]);
for (int j = middle; j >= m.Count; j++)
right.Add(m[j]);
left = mergeSort(left);
right = mergeSort(right);
merge.AddRange(left);
merge.AddRange(right);
for (int k = 0; k < merge.Count; k++)
{
Console.Write(merge[k] + ",");
}
return merge;
}
The problem with your code (apart from the bug Mike Cowan mentioned) is that you’re not performing any actual sorting. You’re first recursively splitting your lists in half (which is correct), but then you’re simply concatenating them back together in their original order, thereby achieving no result:
What you need to do instead is iterate through your two sublists (which, by induction, should have been respectively sorted in the recursive calls), and add elements to the merged list in order.
We start off by comparing the 0th elements:
left[0]againstright[0]. Whichever of the two is smaller, is added to themergelist, and its sublist’s counter is incremented. Suppose thatleft[0] < right[0]: we addleft[0]tomerge, and in the next iteration, we would then need to considerleft[1]againstright[0]. Ifleft[1]is again smaller, we add it tomergeand, in the next iteration, considerleft[2]againstright[0]. Ifright[0]is now the smaller of the two, we add it tomergeand, in the next iteration, compareleft[2]againstright[1]. And so on.This keeps going on until one of the sublists is exhausted. When that happens, we simply add all the elements from the remaining sublist into
merge.Additionally, you should not be writing to console within your recursive method. Move your
Console.Writecalls to yourMainmethod: