How do I sort a two-dimensional array in C#

CsharpProgrammingServer Side Programming

To sort a two-dimensional array in C#, in a nested for loop, add another for loop to check the following condition.

Example

for (int k = 0; k < j; k++) {
   if (arr[i, k] > arr[i, k + 1]) {
      int myTemp = arr[i, k];
      arr[i, k] = arr[i, k + 1];
      arr[i, k + 1] = myTemp;
   }
}

Till the outer loop loops through, use the GetLength() method as shown below. This is done to sort the array.

Example

for (int i = 0; i < arr.GetLength(0); i++) {
   for (int j = arr.GetLength(1) - 1; j > 0; j--) {
      for (int k = 0; k < j; k++) {
         if (arr[i, k] > arr[i, k + 1]) {
            int myTemp = arr[i, k];
            arr[i, k] = arr[i, k + 1];
            arr[i, k + 1] = myTemp;
         }
      }
   }
   Console.WriteLine();
}
raja
Published on 19-Sep-2018 07:01:41
Advertisements