Sort the Matrix based on the given column number
Last Updated :
14 Apr, 2023
Given a Matrix of size M * N (0-indexed) and an integer K, the matrix contains distinct integers only, the task is to sort the Matrix (i.e., the rows of the matrix) by their Values in the Kth column, from Maximum to Minimum. Return the matrix after sorting it.
Examples:
Input: Matrix = [[10, 6, 9, 1], [7, 5, 11, 2], [4, 8, 3, 15]], K = 2
Output: [[7, 5, 11, 2], [10, 6, 9, 1], [4, 8, 3, 15]]
Explanation: In the above Example:
- The index Row 1 has 11 in Column 2, which is the highest, so put it first place.
- The index Row 0 has 9 in Column 2, which is the second highest, so put it in second place.
- The index Row 2 has 3 in Column 2, which is the lowest, so put it in third place.
Input: Matrix = [[3, 4], [5, 6]], K = 0
Output: [[5, 6], [3, 4]]
Explanation: In the above example:
- The index Row 1 has 5 in Column 0, which is the highest, so put it first place.
- The index Row 0 has 3 in Column 0, which is the lowest, so put it in last place.
Approach 1: Using Bubble Sort
This problem can simply be solved by using Bubble sort or some other basic sorting techniques.
- Declare a 2D vector matrix of type integer and initialize it with some values. This matrix represents the input data that needs to be sorted.
- Declare an integer variable k and initialize it with some value. This variable is used to specify the column on which the sorting should be performed.
- Declare two integer variables i and j for use in the following loops.
- Determine the number of rows in the matrix by calling the size method on the matrix vector.
- Use a nested for loop to iterate over the rows and columns of the matrix, starting with the first row and the first column, and comparing the adjacent kth element in each row. If the kth element in the current row is less than the kth element in the next row, swap the two rows.
- Continue this process until all rows have been compared and sorted.
- Print the sorted matrix to the console using nested for loops, iterating over each row and column of the matrix.
Below is the implementation of the above approach.
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector< int > > matrix{ { 4, 8, 3, 5 },
{ 7, 5, 11, 2 },
{ 10, 6, 9, 1 } };
int k = 2;
int i, j;
int rows = matrix.size();
for (i = 0; i < rows - 1; i++) {
for (j = 0; j < rows - i - 1; j++) {
if (matrix[j][k] < matrix[j + 1][k]) {
vector< int > temp = matrix[j];
matrix[j] = matrix[j + 1];
matrix[j + 1] = temp;
}
}
}
cout << "Sorted matrix is : " << endl;
for ( int i = 0; i < matrix.size(); i++) {
for ( int j = 0; j < matrix[i].size(); j++)
cout << matrix[i][j] << " " ;
cout << endl;
}
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int [][] matrix = { { 4 , 8 , 3 , 5 },
{ 7 , 5 , 11 , 2 },
{ 10 , 6 , 9 , 1 } };
int k = 2 ;
int rows = matrix.length;
for ( int i = 0 ; i < rows - 1 ; i++) {
for ( int j = 0 ; j < rows - i - 1 ; j++) {
if (matrix[j][k] < matrix[j + 1 ][k]) {
int [] temp = matrix[j];
matrix[j] = matrix[j + 1 ];
matrix[j + 1 ] = temp;
}
}
}
System.out.println( "Sorted matrix : " );
for ( int [] temp : matrix) {
for ( int it : temp) {
System.out.print(it + " " );
}
System.out.println();
}
}
}
|
Python3
def sort_the_matrix(matrix, k):
n = len (matrix)
for i in range ( 0 , n - 1 ):
for j in range ( 0 , n - i - 1 ):
if matrix[j][k] < matrix[j + 1 ][k]:
matrix[j], matrix[j + 1 ] = matrix[j +
1 ], matrix[j]
print ( "Sorted matrix : " )
N = len (matrix)
M = len (matrix[ 0 ])
for i in range (N):
for j in range (M):
print (matrix[i][j], end = " " )
print ()
matrix = [[ 4 , 8 , 3 , 5 ],
[ 7 , 5 , 11 , 2 ],
[ 10 , 6 , 9 , 1 ]]
K = 2
sort_the_matrix(matrix, K)
|
Javascript
let matrix = [[4, 8, 3, 5], [7, 5, 11, 2], [10, 6, 9, 1]];
let k = 2;
for (let i = 0; i < matrix.length - 1; i++)
{
for (let j = 0; j < matrix.length - i - 1; j++)
{
if (matrix[j][k] < matrix[j + 1][k])
{
let temp = matrix[j];
matrix[j] = matrix[j + 1];
matrix[j + 1] = temp;
}
}
}
console.log( "Sorted matrix is:" );
for (let i = 0; i < matrix.length; i++) {
console.log(matrix[i].join( " " ));
}
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main( string [] args)
{
List<List< int >> matrix = new List<List< int >>()
{
new List< int > { 4, 8, 3, 5 },
new List< int > { 7, 5, 11, 2 },
new List< int > { 10, 6, 9, 1 }
};
int k = 2;
int i, j;
int rows = matrix.Count;
for (i = 0; i < rows - 1; i++)
{
for (j = 0; j < rows - i - 1; j++)
{
if (matrix[j][k] < matrix[j + 1][k])
{
List< int > temp = matrix[j];
matrix[j] = matrix[j + 1];
matrix[j + 1] = temp;
}
}
}
Console.WriteLine( "Sorted matrix is : " );
for ( int m = 0; m < matrix.Count; m++)
{
for ( int n = 0; n < matrix[m].Count; n++)
{
Console.Write(matrix[m][n] + " " );
}
Console.WriteLine();
}
Console.ReadLine();
}
}
|
Output
Sorted matrix is :
7 5 11 2
10 6 9 1
4 8 3 5
Time Complexity: O ( M2 ) M rows
Auxiliary Space: O( N ) N is for storing temp row with N elements while swapping
Approach 2: Using sort( ) function
To solve the problem follow the below steps:
- Create a vector that consists of a pair of elements vector<pair<int, int> v.
- Push the Kth Column Elements In that Vector Along with each row.
- Sort that Column by using the sort function.
- Reverse the vector.
- Now create a 2D vector and push each element from the vector to the corresponding row along with the same column number of the vector resultant.
- Return new 2D vector.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<vector< int > >
sortTheMatrix(vector<vector< int > >& matrix, int k)
{
int n = matrix.size();
vector<pair< int , int > > v;
for ( int i = 0; i < n; i++) {
v.push_back({ matrix[i][k], i });
}
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
vector<vector< int > > a;
for ( auto & it : v) {
a.push_back(
matrix[it.second]);
}
return a;
}
void print(vector<vector< int > > matrix, int k)
{
vector<vector< int > > ans = sortTheMatrix(matrix, k);
cout << "Sorted Matrix Based on column 2 Values :"
<< endl;
int N = ans.size();
int M = ans[0].size();
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
cout << ans[i][j] << " " ;
}
cout << '\n' ;
}
}
int main()
{
vector<vector< int > > matrix = { { 10, 6, 9, 1 },
{ 7, 5, 11, 2 },
{ 4, 8, 3, 15 } };
int K = 2;
print(matrix, K);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static List<List<Integer>> sortTheMatrix(List<List<Integer>> matrix, int k) {
int n = matrix.size();
List<Tuple<Integer, Integer>> v = new ArrayList<>();
for ( int i = 0 ; i < n; i++) {
v.add( new Tuple<>(matrix.get(i).get(k), i));
}
Collections.sort(v, new Comparator<Tuple<Integer, Integer>>() {
@Override
public int compare(Tuple<Integer, Integer> x, Tuple<Integer, Integer> y) {
return x.item1.compareTo(y.item1);
}
});
Collections.reverse(v);
List<List<Integer>> a = new ArrayList<>();
for (Tuple<Integer, Integer> item : v) {
a.add(matrix.get(item.item2));
}
return a;
}
public static void print(List<List<Integer>> matrix, int k) {
List<List<Integer>> ans = sortTheMatrix(matrix, k);
System.out.println( "Sorted Matrix Based on column " + (k ) + " Values:" );
for (List<Integer> row : ans) {
for ( int value : row) {
System.out.print(value + " " );
}
System.out.println();
}
}
public static void main(String[] args) {
List<List<Integer>> matrix = Arrays.asList(
Arrays.asList( 10 , 6 , 9 , 1 ),
Arrays.asList( 7 , 5 , 11 , 2 ),
Arrays.asList( 4 , 8 , 3 , 15 )
);
int K = 2 ;
print(matrix, K);
}
}
class Tuple<X, Y> {
public final X item1;
public final Y item2;
public Tuple(X x, Y y) {
this .item1 = x;
this .item2 = y;
}
}
|
Python3
def sortTheMatrix(matrix, k):
n = len (matrix)
v = []
for i in range (n):
v.append((matrix[i][k], i))
v.sort()
v = v[:: - 1 ]
a = []
for it in v:
a.append(matrix[it[ 1 ]])
return a
def print_matrix(matrix, k):
ans = sortTheMatrix(matrix, k)
print ( "Sorted Matrix Based on column {} Values :" . format (k))
N = len (ans)
M = len (ans[ 0 ])
for i in range (N):
for j in range (M):
print (ans[i][j], end = " " )
print ()
matrix = [[ 10 , 6 , 9 , 1 ],
[ 7 , 5 , 11 , 2 ],
[ 4 , 8 , 3 , 15 ]]
K = 2
print_matrix(matrix, K)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static List<List< int > >
sortTheMatrix(List<List< int > > matrix, int k)
{
int n = matrix.Count;
List<Tuple< int , int > > v
= new List<Tuple< int , int > >();
for ( int i = 0; i < n; i++) {
v.Add(Tuple.Create(matrix[i][k], i));
}
v.Sort((x, y) = > x.Item1.CompareTo(y.Item1));
v.Reverse();
List<List< int > > a = new List<List< int > >();
foreach (Tuple< int , int > item in v)
{
a.Add(matrix[item.Item2]);
}
return a;
}
static void print(List<List< int > > matrix, int k)
{
List<List< int > > ans = sortTheMatrix(matrix, k);
Console.WriteLine(
"Sorted Matrix Based on column 2 Values :" );
foreach (List< int > row in ans)
{
foreach ( int value in row)
{
Console.Write(value + " " );
}
Console.WriteLine();
}
}
static void Main()
{
List<List< int > > matrix = new List<List< int > >{
new List< int >{ 10, 6, 9, 1 },
new List< int >{ 7, 5, 11, 2 },
new List< int >{ 4, 8, 3, 15 }
};
int K = 2;
print(matrix, K);
}
}
|
Javascript
function sortTheMatrix(matrix, k) {
const n = matrix.length;
const v = [];
for (let i = 0; i < n; i++) {
v.push([(matrix[i][k]), i]);
}
v.sort((a, b) => a[0] - b[0]);
v.reverse();
const a = [];
for (const [value, index] of v) {
a.push(matrix[index]);
}
return a;
}
function print(matrix, k) {
const ans = sortTheMatrix(matrix, k);
console.log(`Sorted Matrix Based on column ${k + 1} Values:`);
for (const row of ans) {
console.log(row.join( ' ' ));
}
}
const matrix = [
[10, 6, 9, 1],
[7, 5, 11, 2],
[4, 8, 3, 15],
];
const K = 2;
print(matrix, K);
|
Output
Sorted Matrix Based on column 2 Values :
7 5 11 2
10 6 9 1
4 8 3 15
Time Complexity: O(N*logN) i., e O(N) running for loop and LogN for STL.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...