-6

If the parameter was an int[][] called arry, how would you find the median of it?

Sorry if my formatting is wrong, it's my first time here.

The median of the entire 2d array counting every int in the array.

All the rows are the same length, for example:

1 4 3 2 5

4 5 3 2 9

4 7 8 98 24

user3397448
  • 1
  • 1
  • 4

2 Answers2

0

If I interpret your question correctly, you would do it the same way you find the median of any set of numbers:

  1. Go through each element in the 2D array, adding each number to a temporary list.
  2. Sort the list.
  3. Grab the center element (if list length is odd) or the mean of the two centers (if list length is even).

As long as you get all of the numbers you wish to include in your calculation into a sorted list of some sort, you can find the median. If your original data isn't in a good form for this (e.g. a 2D array, or any other data structure), you'll have to create a temporary list to use during the calculation.

An ArrayList<Integer> is a good choice, by the way.

Jason C
  • 34,234
  • 12
  • 103
  • 151
0

Please delete one of your questions, you made two almost identical questions..

import java.util.Arrays;

public class Median {

public static void main(String[] args) {
    int[][] array2d = {
            {1, 4, 3, 2, 5},
            {4, 5, 3, 2, 9},
            {4, 7, 8, 98, 24}
    };
    // Create a new list to store the items
    int[] list = new int[array2d.length*array2d[0].length];
    // keep track of where we are.
    int listPos = 0;
    // iterate over the entire 2d array adding each integer
    for(int i = 0 ; i < array2d.length; i++) {
        for(int j = 0; j < array2d.length; j++) {
            list[listPos++] = array2d[i][j];
        }
    }
    // sort the list.
    Arrays.sort(list);
    System.out.println(median(list));
}

/**
 * Finds the median in an Array of integers.
 * @param m Array of integers
 * @return the median value
 */
public static double median(int[] m) {
    int middle = m.length/2;
    if (m.length%2 == 1) {
        return m[middle];
    } else {
        return (m[middle-1] + m[middle]) / 2.0;
    }
}

}

Tristan
  • 2,189
  • 14
  • 11