Home ProgrammingJava Find smallest number from each column of a matrix

Find smallest number from each column of a matrix

by Log Raj Bhatt
0 comment 962 views

Today I want to solve a  small problem using java programming language. This Problem consists of finding smallest number from each column of a matrix. If you are being confused, Let’s be clear about problem.


Suppose we have a 2D array of Numbers.  Here I may use term Matrix for 2D array. We know there are columns and rows in each matrix. Now We have to find the location of smallest element in the column. Or question can be In which row the smallest number of this column exists. Or We can say what is the location of the smallest number in each column. Here we can assume that each row in the matrix have equal number of elements. I assume a matrix like below.


{2.0, 3.0, 4.0, 6.0},

{3.0, 6.0, 7.0, 3.3},

{2.1, 3.4, 2.0, 7.7}


For Example, In above matrix first column is,




After solution we will find, In the column 2.0 is the smallest number and it is in the first row. Or we can say [0][0] is the location of smallest element of first column.

Now let’s move our discussion to solution of this problem.


Solution here I want to give by code itself. Here is small piece of code written in java. So first have look at the code then I’ll try to describe the code in brief.

public class MainTest {
public void findSmallestElementColumnwiseIn2dArray(double arr[][]) {
for(int j=0;j<arr[0].length;j++)
int row = 0;
for (int i = 1; i < arr.length; i++) {
row = (arr[row][j] < arr[i][j]) ? row : i;
System.out.println("Column = " + j + " Row = " + row);

I tried to give the meaningful name to method so it went so long. Here we are getting an 2D array as an input in argument. First for loop in the code means for every column. Index j represent column of matrix in this code. The variable row is the location smallest element of column. Let it be 0 initially. We now compare the smallest element at rowth row of the jth column with element at each row of the jth column. And ultimately we will find the smallest number in column.

Complexity Analysis:

Outer loop executes array[0].length times. That is same as number of columns. Inner loop executes arr.length times. arr.length is same as number of rows in matrix.

So I conclude that if matrix have n rows and m columns, complexity of this solution is O(m*n).

Execute the above code with following main.

public static void main(String[] args) {
double arr[][] = {
{2, 3, 4, 6},
{3, 6, 7, 3.3},
{2.1, 3.4, 2, 7.7}
MainTest ma=new MainTest();

After executing this you will get output like,
Column = 0 Row = 0
Column = 1 Row = 0
Column = 2 Row = 2
Column = 3 Row = 1

Here the index of smallest number is output for each column. If you look at input array, You will find smallest number of first column in first row….and smallest number of 4th column in 2nd row.

0 comment

Related Articles

Do NOT follow this link or you will be banned from the site!