Hello, I have a task that I can not solve, could not help me. Given a square matrix by rearranging rows and columns, arrange the elements of the diagonal in descending order in C #.

Here I wrote the code, but why doesn't it sort the diagonals

static void Main(string[] args) { int buf = 0; int[, ] mass = new int[4, 4]; Random rand = new Random(); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) mass[i, j] = rand.Next(10); //вывод матрици for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Console.Write(mass[i, j]); } Console.WriteLine(" "); } for (int i = 0; i < 4; i++) for (int j = 0; j < 3; j++) if (i == j) if (mass[i, j] > mass[i + 1, j + 1]) { // перестановка строк for (int s = 0; s < 1; s++) for (int k = 0; k < 4; k++) { buf = mass[s, k]; mass[s, k] = mass[s + 1, k]; mass[s + 1, k] = buf; } // перестановка столбцов for (int s = 0; s < 4; s++) for (int k = 0; k < 1; k++) { buf = mass[s, k]; mass[s, k] = mass[s, k + 1]; mass[s, k + 1] = buf; } } Console.WriteLine(" "); //вывод for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Console.Write(mass[i, j]); } Console.WriteLine(" "); } } } } 
  • @ Alex031, According to the rules of the forum, questions should not be limited to the decision or the completion of student assignments. Please clarify what you have done yourself and what did not work out. - Pavel Azanov
  • I can not think of the algorithm itself. - Alex031
  • one
    @ Alex031 as it was correctly stated above, they do not perform assignments here, do not write laboratory tests, and do not invent algorithms for students. They will be happy to help you on the condition that you have already done something yourself, and do not expect someone to do your work for you. - DreamChild
  • Updated kodu - Alex031
  • so you need C or C #? - DreamChild

1 answer 1

See it. Your task naturally falls into the following subtasks:

  1. Swap the i and j th row of the matrix.
  2. Sort rows by a key equal to the corresponding diagonal element.

As a sorting for the educational task is quite suitable bubble.

Then try it yourself.

[Yes, the solution is not optimal, one could first determine the necessary permutation, working with a diagonal, and only then rearrange the lines.]

Update

Well, swapping rows is an expensive operation compared to swapping their indexes. Therefore, it would be cheaper to first sort the indices, and then determine the permutation of rows by sorted indexes, decompose it into a product of cycles, and transpose the rows — thus, each element is rearranged once (plus once per cycle).

  • Sorry, you can read more about the fact that the solution is not optimal - Alex031
  • Well, swapping rows is an expensive operation compared to swapping their indexes. Therefore, it would be cheaper to first sort the indices, and then determine the permutation of rows by sorted indexes, decompose it into a product of cycles, and transpose the rows — thus, each element is rearranged once (plus once per cycle). - VladD