5. Sorting a Matrix

5. Sorting a Matrix


Problem link :- click here


package progams;

import java.util.Arrays;
import java.util.Scanner;

public class Matrix__5
{
	/*
	    Given an NxN matrix. we have to sort all the elements of the matrix
	    		also given that     	time complexity :-  O( N^2 log(N) )
	    		and 				space complexity :- O( N^2 )
	    
	    so we can just store all the elements in an array
	    and sort that array (you can use quick sort or merge sort)
	    		but time complexity of quick and merge sort would be  O(N^2      log(N^2)  )     right?
	    													      O(N^2     2 log(N)    )
	    													      O(N^2      log(N)      )
	    			because we neglect constants while writing time complexity in O
	    and at last update the matrix
	*/
	
	static void sortMatrix(int mat[][], int n)
	{
		int i, j;
		int temp[] = new int[n*n];
		
		int k = 0;
		for(i=0; i<n; i++)
			for(j=0; j<n; j++)
				temp[k++] = mat[i][j];
		
		Arrays.sort(temp);
		
		k = 0;
		for(i=0; i<n; i++)
			for(j=0; j<n; j++)
				mat[i][j] = temp[k++];
		
	}
	
	public static void main(String[] args)
	{
		int i, j, r, c;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the number of rows : ");
		r = s.nextInt();
		System.out.print("Enter the numvber of columns : ");
		c = s.nextInt();
		int matrix[][] = new int[r][c];
		System.out.println("Enter the elements of the matrix : ");
		for(i=0; i<r; i++)
		{
			for(j=0; j<c; j++)
				matrix[i][j] = s.nextInt();
		}
		System.out.println("Given matrix : ");
		printMatrix(matrix, r, c);

		sortMatrix(matrix, r);
		System.out.println("\nMatrix after sorting : ");
		printMatrix(matrix, r, c);
	}

	static void printMatrix(int mat[][], int r, int c)
	{
		for(int i=0; i<r; i++)
		{
			for(int j=0; j<c; j++)
				System.out.print(mat[i][j] + "  ");
			System.out.println();
		}
	}
}

Time complexity :- O( n2 log(n) )
Space complexity :- O( n2 )

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree