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();
// 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();
}
}
OutputSorted 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);
OutputSorted 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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem