Finding minimum and maximum in Java 2D array

前端 未结 4 1288
栀梦
栀梦 2020-12-21 13:02

I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two way

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 13:44

    Your problem is: You are sorting the array of int arrays instead of sorting each individual int in each int array.

    To solve this: Loop through each int array in the array of int arrays.

    Instructions for finding the maximum and minimum of a 2D int array using Arrays.sort():

    1. Declare a 2D int array to sort called data.
    2. Declare two ints, one to hold the maximum value, the other the minimum value.
      • The initial value of the maximum should be Integer.MIN_VALUE and the initial value of the minimum should be Integer.MAX_VALUE to make sure that negative values are handled.
    3. Loop through data from 0 to data.length:
      1. Sort data[i]
      2. Check if the first value of data[i] is less than the minimum and change it if it is.
      3. Check if the last value of data[i] is greater than the maximum and change it if it is.
    4. Output your result.

    Example:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[][] data = {{3, 2, 5},
                {1, 4, 4, 8, 13},
                {9, 1, 0, 2},
                {0, 2, 6, 3, -1, -8} };
    
            int maximum = Integer.MIN_VALUE;
            int minimum = Integer.MAX_VALUE;
    
            for(int i = 0; i < data.length; i++) {
                Arrays.sort(data[i]);
    
                if(data[i][0] < minimum) minimum = data[i][0];
                if(data[i][data[i].length - 1] > maximum) maximum = data[i][data[i].length - 1];
            }
    
            System.out.println("Minimum = " + maximum);  
            System.out.println("Maximum = " + minimum); 
        }
    }
    

提交回复
热议问题