-1
public static void main(String[] args) {
    // TODO code application logic here
    int numRows = 5;
    int numCols = numRows;
    int[][] twoDimArray = new int[numRows][numCols];
    Random randGen = new Random();

    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            int randIndex = randGen.nextInt(4);
            int value = randGen.nextInt(100);
            twoDimArray[i][j] = value;
        }
    }
    System.out.println("\nThe two-dimensional array: ");
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            System.out.print(twoDimArray[i][j] + " ");
        }
        System.out.println();

    }  
    }
}

I want to find a local minimum using a "brute force" approach. I know with a one dimensional array I would use a for-loop to compare all the elements in the array until I found a local minimum, but I don't know how to do that here.

Edit: Could I use binary search instead? Find the middle row and search there and if one isn't found, I search one of the halves.

  • 1
    How would you define a local minimum in the context of a 2D array? Which neighboring elements would be used to determine if there was a local minimum? – 4castle Oct 27 '16 at 03:38
  • a local minimum in a 2D array has to be the minimum element in it's row and smaller than the element right "on top" of it and directly "below it". so if i is an element in the row and j is an element in a column, the local minimum has to be less than [i-1], [i+1], [j-1], and [j+1] – Nicholas Whitfield Oct 27 '16 at 03:45
  • There isn't really an optimized way to find a local minimum in terms of time complexity. Since the data is unsorted and presumably can contain duplicates, there are very few optimizations that can be made. [See this post](http://stackoverflow.com/a/12238349/5743988). – 4castle Oct 27 '16 at 04:34

1 Answers1

1

The brute force method would be very similar to that of a 1D array, just with an extra loop, and a few more checks:

public int[] findLocalMinimum(int[][] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {

            int current = arr[i][j];

            if (i + 1 < arr.length    && current >= arr[i + 1][j] ||
                i - 1 >= 0            && current >= arr[i - 1][j] ||
                j + 1 < arr[i].length && current >= arr[i][j + 1] ||
                j - 1 >= 0            && current >= arr[i][j - 1]) {
                continue;
            } else {
                return new int[] { i, j };
            }

        }
    }
    return new int[] { -1, -1 };
}
4castle
  • 32,613
  • 11
  • 69
  • 106