Sort the Matrix based on the given column number
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(); // Bubble sort logic for (i = 0; i < rows - 1; i++) { for (j = 0; j < rows - i - 1; j++) { // Comparing the adjacent kth element if (matrix[j][k] < matrix[j + 1][k]) { // Storing whole row in temp vector< int > temp = matrix[j]; matrix[j] = matrix[j + 1]; matrix[j + 1] = temp; } } } // Printing the matrix 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; } // This code is contributed by aeroabrar_31 |
Java
/*package whatever //do not write package name here */ 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; // Bubble sort logic for ( int i = 0 ; i < rows - 1 ; i++) { for ( int j = 0 ; j < rows - i - 1 ; j++) { // comparing the adjacent kth element if (matrix[j][k] < matrix[j + 1 ][k]) { // swapping adjacent rows int [] temp = matrix[j]; // storing whole // row in temp matrix[j] = matrix[j + 1 ]; matrix[j + 1 ] = temp; } } } System.out.println( "Sorted matrix : " ); // printing the matrix after sorting for ( int [] temp : matrix) { for ( int it : temp) { System.out.print(it + " " ); } System.out.println(); } } } // This code is contributed by aeroabrar_31 |
Python3
def sort_the_matrix(matrix, k): n = len (matrix) # bubble sort logic for i in range ( 0 , n - 1 ): for j in range ( 0 , n - i - 1 ): # comparing the adjacent kth element if matrix[j][k] < matrix[j + 1 ][k]: matrix[j], matrix[j + 1 ] = matrix[j + 1 ], matrix[j] # swapping rows # printing the sorted matrix 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 () # Driver's code 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; // Bubble sort logic for (let i = 0; i < matrix.length - 1; i++) { for (let j = 0; j < matrix.length - i - 1; j++) { // Comparing the adjacent kth element if (matrix[j][k] < matrix[j + 1][k]) { // Storing whole row in temp let temp = matrix[j]; matrix[j] = matrix[j + 1]; matrix[j + 1] = temp; } } } // Printing the matrix console.log( "Sorted matrix is:" ); for (let i = 0; i < matrix.length; i++) { console.log(matrix[i].join( " " )); } // This code is contributed by rutikbhosale |
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; // Bubble sort logic for (i = 0; i < rows - 1; i++) { for (j = 0; j < rows - i - 1; j++) { // Comparing the adjacent kth element if (matrix[j][k] < matrix[j + 1][k]) { // Storing whole row in temp List< int > temp = matrix[j]; matrix[j] = matrix[j + 1]; matrix[j + 1] = temp; } } } // Printing the matrix 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(); } } |
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++
// C++ Program to sort the matrix based // on the column values. #include <bits/stdc++.h> using namespace std; vector<vector< int > > sortTheMatrix(vector<vector< int > >& matrix, int k) { // Rows int n = matrix.size(); vector<pair< int , int > > v; for ( int i = 0; i < n; i++) { // Kth col in ith row and // their ith row value v.push_back({ matrix[i][k], i }); } // Based on increasing manner // of kth col sort(v.begin(), v.end()); // Based on decreasing manner // of kth col reverse(v.begin(), v.end()); vector<vector< int > > a; for ( auto & it : v) { a.push_back( // Now put each row one by // one into our ans in // decresing manner(based // on Kth col) matrix[it.second]); } return a; } // Print function 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' ; } } // Drivers code int main() { vector<vector< int > > matrix = { { 10, 6, 9, 1 }, { 7, 5, 11, 2 }, { 4, 8, 3, 15 } }; int K = 2; // Function Call print(matrix, K); return 0; } |
Java
import java.util.*; public class Main { public static List<List<Integer>> sortTheMatrix(List<List<Integer>> matrix, int k) { // Rows int n = matrix.size(); // Create a list of pairs containing the value at // the k-th column and the index of the row List<Tuple<Integer, Integer>> v = new ArrayList<>(); for ( int i = 0 ; i < n; i++) { v.add( new Tuple<>(matrix.get(i).get(k), i)); } // Sort the list based on increasing order of the // k-th column 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); } }); // Reverse the list to get decreasing order of the // k-th column Collections.reverse(v); // Create a new matrix and add the rows to it in // decreasing order of the k-th column List<List<Integer>> a = new ArrayList<>(); for (Tuple<Integer, Integer> item : v) { a.add(matrix.get(item.item2)); } return a; } // print function 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(); } } // Driver's code 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 ; // function call 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
# Python Program to sort the matrix based # on the column values. def sortTheMatrix(matrix, k): # Rows n = len (matrix) v = [] for i in range (n): # Kth col in ith row and # their ith row value v.append((matrix[i][k], i)) # Based on increasing manner # of kth col v.sort() # Based on decreasing manner of kth col v = v[:: - 1 ] a = [] for it in v: # Now put each row one by # one into our ans in # decresing manner(based # on Kth col) a.append(matrix[it[ 1 ]]) return a # Print function 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 () # Drivers code matrix = [[ 10 , 6 , 9 , 1 ], [ 7 , 5 , 11 , 2 ], [ 4 , 8 , 3 , 15 ]] K = 2 # Function Call print_matrix(matrix, K) # This code is contributed by prasad264 |
C#
// C# program to sort the matrix based // on the column values using System; using System.Collections.Generic; using System.Linq; class Program { static List<List< int > > sortTheMatrix(List<List< int > > matrix, int k) { // Rows int n = matrix.Count; // Create a list of pairs containing the value at // the k-th column and the index of the row 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)); } // Sort the list based on increasing order of the // k-th column v.Sort((x, y) = > x.Item1.CompareTo(y.Item1)); // Reverse the list to get decreasing order of the // k-th column v.Reverse(); // Create a new matrix and add the rows to it in // decreasing order of the k-th column List<List< int > > a = new List<List< int > >(); foreach (Tuple< int , int > item in v) { a.Add(matrix[item.Item2]); } return a; } // print function 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(); } } // Driver's code 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; // function call print(matrix, K); } } |
Javascript
// JavaScript Program to sort the matrix based // on the column values. // Function to sort the matrix based on column values function sortTheMatrix(matrix, k) { // Rows const n = matrix.length; // Create a list of pairs containing the value at // the k-th column and the index of the row const v = []; for (let i = 0; i < n; i++) { v.push([(matrix[i][k]), i]); } // Sort the list based on increasing order of the // k-th column v.sort((a, b) => a[0] - b[0]); // Reverse the list to get decreasing order of the // k-th column v.reverse(); // Create a new matrix and add the rows to it in // decreasing order of the k-th column const a = []; for (const [value, index] of v) { a.push(matrix[index]); } return a; } // Print function 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( ' ' )); } } // Driver's code const matrix = [ [10, 6, 9, 1], [7, 5, 11, 2], [4, 8, 3, 15], ]; const K = 2; // Function call print(matrix, K); |
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)
Please Login to comment...