Skip to content
Related Articles

Related Articles

Improve Article

Sort the major diagonal of the matrix

  • Difficulty Level : Medium
  • Last Updated : 12 Apr, 2021

Given a matrix mat[][], the task is to sort the main diagonal elements of the matrix in increasing order.
Main Diagonal: Main diagonal or major diagonal of a matrix is the collection of elements mati, j, where i == j
Examples: 
 

Input: mat[][] = {{4, 2}, {3, 1}}
Output: 
1 2
3 4
Explanation:
In the given matrix, the diagonal elements are -
=> {mat[0][0], mat[1][1]}
=> {4, 1}
=> Sorted Order = {1, 4}

Input: mat[][] = {{9, 4}, {3, 4}}     
Output: 
4 4
3 9
Explanation:
In the given matrix, the diagonal elements are -
=> {mat[0][0], mat[1][1]}
=> {9, 4}
=> Sorted Order = {4, 9}

 

Approach: The idea is modify the selection sort to sort the diagonal elements of the matrix. Count of the diangonal elements of matrix M*N will be min(M, N). As we know the major diagonal elements of the matrix are mati, j where i == j. Therefore, the ith element of the major diagonal of the matrix will be mat[i][i]. Hence, repeatedly find the minimum element from the major diagonal of the matrix and put it at the beginning. 
Below is the implementation of the above approach:
 

C++




// C++ implementation to sort the
// major diagonal of the matrix
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to sort the major
// diagonal of the matrix
void sortDiagonal(int a[2][2], int M, int N)
{
    // Loop to find the ith minimum
    // element from the major diagonal
    for (int i = 0; i < M; i++) {
        int sm = a[i][i];
        int pos = i;
         
        // Loop to find the minimum
        // element from the unsorted matrix
        for (int j = i + 1; j < N; j++) {
            if (sm > a[j][j]) {
                sm = a[j][j];
                pos = j;
            }
        }
         
        // Swap to put the minimum
        // element at the beginning of
        // the major diagonal of matrix
        swap(a[i][i], a[pos][pos]);
    }
 
    // Loop to print the matrix
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++)
            cout << a[i][j] << " ";
        cout << endl;
    }
}
 
// Driven Code
int main()
{
    int a[2][2] = { { 4, 2 },
                    { 3, 1 } };
 
    // Sort the major Diagonal
    sortDiagonal(a, 2, 2);
 
    return 0;
}

Java




// Java implementation to sort the
// major diagonal of the matrix
class GFG{
  
// Function to sort the major
// diagonal of the matrix
static void sortDiagonal(int a[][], int M, int N)
{
    // Loop to find the ith minimum
    // element from the major diagonal
    for (int i = 0; i < M; i++) {
        int sm = a[i][i];
        int pos = i;
          
        // Loop to find the minimum
        // element from the unsorted matrix
        for (int j = i + 1; j < N; j++) {
            if (sm > a[j][j]) {
                sm = a[j][j];
                pos = j;
            }
        }
          
        // Swap to put the minimum
        // element at the beginning of
        // the major diagonal of matrix
        swap(a, i, i, pos, pos);
    }
  
    // Loop to print the matrix
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++)
            System.out.print(a[i][j]+ " ");
        System.out.println();
    }
}
  
static void swap(int[][] a, int i, int i2, int pos, int pos2) {
    int temp = a[i][i2];
    a[i][i2] = a[pos][pos2];
    a[pos][pos2] = temp;   
}
 
// Driven Code
public static void main(String[] args)
{
    int a[][] = { { 4, 2 },
                    { 3, 1 } };
  
    // Sort the major Diagonal
    sortDiagonal(a, 2, 2);
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python3 implementation to sort the
# major diagonal of the matrix
 
# Function to sort the major
# diagonal of the matrix
def sortDiagonal(a, M, N):
     
    # Loop to find the ith minimum
    # element from the major diagonal
    for i in range(M):
        sm = a[i][i]
        pos = i
         
        # Loop to find the minimum
        # element from the unsorted matrix
        for j in range(i + 1 , N):
            if (sm > a[j][j]):
                sm = a[j][j]
                pos = j
                 
        # Swap to put the minimum
        # element at the beginning of
        # the major diagonal of matrix
        a[i][i], a[pos][pos] = a[pos][pos] , a[i][i]
         
    # Loop to print the matrix
    for i in range(M):
        for j in range(N):
            print(a[i][j],end=" ")
        print()
 
# Driven Code
a = [[4, 2],[3, 1]]
 
# Sort the major Diagonal
sortDiagonal(a, 2, 2)
 
# This code is contributed by shubhamsingh10

C#




// C# implementation to sort the
// major diagonal of the matrix
using System;
 
class GFG{
   
// Function to sort the major
// diagonal of the matrix
static void sortDiagonal(int[,]a, int M, int N)
{
    // Loop to find the ith minimum
    // element from the major diagonal
    for (int i = 0; i < M; i++) {
        int sm = a[i, i];
        int pos = i;
           
        // Loop to find the minimum
        // element from the unsorted matrix
        for (int j = i + 1; j < N; j++) {
            if (sm > a[j, j]) {
                sm = a[j, j];
                pos = j;
            }
        }
           
        // Swap to put the minimum
        // element at the beginning of
        // the major diagonal of matrix
        swap(a, i, i, pos, pos);
    }
   
    // Loop to print the matrix
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++)
            Console.Write(a[i, j]+ " ");
        Console.WriteLine();
    }
}
   
static void swap(int[,] a, int i, int i2, int pos, int pos2) {
    int temp = a[i, i2];
    a[i, i2] = a[pos, pos2];
    a[pos, pos2] = temp;   
}
  
// Driven Code
public static void Main(String[] args)
{
    int[,]a = { { 4, 2 },
                    { 3, 1 } };
   
    // Sort the major Diagonal
    sortDiagonal(a, 2, 2);
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// Javascript implementation to sort the
// major diagonal of the matrix
 
// Function to sort the major
// diagonal of the matrix
function sortDiagonal(a, M, N)
{
    // Loop to find the ith minimum
    // element from the major diagonal
    for (var i = 0; i < M; i++) {
        var sm = a[i][i];
        var pos = i;
         
        // Loop to find the minimum
        // element from the unsorted matrix
        for (var j = i + 1; j < N; j++) {
            if (sm > a[j][j]) {
                sm = a[j][j];
                pos = j;
            }
        }
         
        // Swap to put the minimum
        // element at the beginning of
        // the major diagonal of matrix
        temp = a[i][i]
        a[i][i] = a[pos][pos]
        a[pos][pos] = temp
    }
 
    // Loop to print the matrix
    for (var i = 0; i < M; i++) {
        for (var j = 0; j < N; j++)
            document.write( a[i][j] + " ");
        document.write("<br>");
    }
}
 
// Driven Code
var a = [ [ 4, 2 ],
                [ 3, 1 ] ];
// Sort the major Diagonal
sortDiagonal(a, 2, 2);
 
// This code is contributed by noob2000.
</script>
Output: 
1 2 
3 4

 

Performance Analysis: 
 



  • Time Complexity: O(min(M, N)2)
  • Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :