public List<int> MergeSort(List<int> m) {
if (m.Count() <= 1) return m;
int mid = m.Count() / 2;
List<int> left = new List<int>(), right = new List<int>();
for (int i = 0; i < mid; i++) left.Add(m[i]);
for (int i = mid; i < m.Count(); i++) right.Add(m[i]);
left = MergeSort(left);
right = MergeSort(right);
return Merge(left, right);
}
public List<int> Merge(List<int> a, List<int> b) {
int aCount = 0, bCount = 0;
List<int> m = new List<int>();
while (m.Count() < a.Count() + b.Count()) {
if (aCount < a.Count() && bCount < b.Count())
m.Add(a[aCount] < b[bCount] ? a[aCount++] : b[bCount++]);
else
m.Add(aCount < a.Count() ? a[aCount++] : b[bCount++]);
}
return m;
}
if (m.Count() <= 1) return m;
int mid = m.Count() / 2;
List<int> left = new List<int>(), right = new List<int>();
for (int i = 0; i < mid; i++) left.Add(m[i]);
for (int i = mid; i < m.Count(); i++) right.Add(m[i]);
left = MergeSort(left);
right = MergeSort(right);
return Merge(left, right);
}
public List<int> Merge(List<int> a, List<int> b) {
int aCount = 0, bCount = 0;
List<int> m = new List<int>();
while (m.Count() < a.Count() + b.Count()) {
if (aCount < a.Count() && bCount < b.Count())
m.Add(a[aCount] < b[bCount] ? a[aCount++] : b[bCount++]);
else
m.Add(aCount < a.Count() ? a[aCount++] : b[bCount++]);
}
return m;
}
I realize that nowadays when I practice interview questions I'm tending less towards readability and convention (using var for local variables in C#) in favor of less lines of code (using var means you have to declare each variable on a separate line of code) - when doing interview practice you just wanna get the answer on the page and move on. I could have refactored the while loop in my Merge function into many more lines of code but opted for the a cryptic version instead, which makes me feel like a boss but may be more confusing to readers the first time through. So I apologize for that