I'm trying to figure out how to sort a 2 dimensional array. I've seen this question posted for other languages, but not C#. I'm working on a coding challenge where the input is in the form of a 2 dimensional array and I need to sort by the first column.
I'm thinking to create an extension method for a 2 dimensional int array that takes a parameter for the left column or the right, but not sure what would be be the best sorting algorithm for that. I figured I could convert the 2D int array to a SortedDictionary then convert it back, but it seems like it would be inefficient if I convert it back to a 2D array again. Would it be best to convert to a SortedDictionary and leave it in that data type or does someone have an amazing sorting algorithm for 2D arrays?
public static int[][] Sort(this int[][] a2DArr, bool sortLeftCol = true)
{
SortedDictionary<int, int> sd = new SortedDictionary<int, int>();
int[][] sorted2Darr = new int[a2DArr.Count()][];
if (sortLeftCol == true)
{
for (int i = 0; i < a2DArr.Count(); i++)
{ sd.Add(a2DArr[i][0], a2DArr[i][1]); }
for (int i = 0; i < a2DArr.Count(); i++)
{
sorted2Darr[i][0] = sd.ElementAt(i).Key;
sorted2Darr[i][1] = sd.ElementAt(i).Value;
}
}
else //sort by right column
{
for (int i = 0; i < a2DArr.Count(); i++)
{ sd.Add(a2DArr[i][1], a2DArr[i][0]); }
for (int i = 0; i < a2DArr.Count(); i++)
{
sorted2Darr[i][0] = sd.ElementAt(i).Value;
sorted2Darr[i][1] = sd.ElementAt(i).Key;
}
}
return sorted2Darr;
}