Find the maximum value of a two-dimensional array and its position

Find the maximum value of a two-dimensional array and its position-Java implementation


Example:

Encapsulate a type of MatrixLocation to query the maximum value and its location in a two-dimensional array. The maximum value is stored in double type maxValue, and the position is stored in int type row and column. Encapsulate the execution main class, given a two-dimensional array, output the maximum value and its position. Encapsulate the main class of execution.

This question is a simple two-dimensional array search problem, the maximum value can be found by traversing the two-dimensional array.
Code implementation (Java)

public class Main{
    
    
	public static void main()(String[] args){
    
    
		double[][] array={
    
    {
    
    3,16,9,12,29},{
    
    23,18,39,58,36},{
    
    27,35,56,48,6}}; //静态初始化一个doble型的二维数组
		MatrixLocation.maxvalue(array);   //调用maxvalue方法,输出二维数组中的最大值及其坐标(下标从0开始)
	}
}
public class MatrixLocation {
    
    
    public static void maxvalue(double[][] a){
    
      //maxvalue是类方法
        double maxValue=a[0][0];  //先将a[0][0]赋值给maxValue
        int row=0,column=0;
        for(int i=0;i<a.length;i++){
    
       //遍历、比较
            for(int j=0;j<a[0].length;j++){
    
    
                if(a[i][j]>maxValue){
    
    
                    maxValue=a[i][j];
                    row=i;
                    column=j;
                }
            }
        }
        System.out.println("该二维数组中的最大值是"+maxValue);
        System.out.println("最大值的在数组中的下标是:"+row+" "+column);
    }
}

The matrix method in the MatrixLocation class above can actually have some problems. It can only output the position of the maximum value in the array for the first time. This is because the subscript of the maximum value is indicated by int row and int column. If you write it yourself, you can use the other two arrays to store the row subscript and column subscript of the maximum value respectively, so that the maximum value can be output at all positions in the array.

Guess you like

Origin blog.csdn.net/m0_46772594/article/details/105773591