Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search a 2 dimensional array in java

Tags:

java

arrays

How does one iterate through a two dimensional array search for [ ] [Name]?

When the Name is found the Index should be returned so that I can change the values in that array.

[Index] [Values].

Also, how does the syntax look for the storing to the array found? [ ] [index]. Loop through index and set a value. [0] [1] = blah.

Thanks

like image 989
some_id Avatar asked Dec 07 '10 13:12

some_id


People also ask

How do you check if an element is present in a 2D array?

You could simplify by using if (found) cout << "0 exists in the matrix\n"; No need for the c variable. If x == 1 and found == true , your outer loop will iterate again.

Can we do binary search in 2D array?

To perform a Binary search in the 2D array, the array needs to be sorted. Here is an unsorted 2D array is given, so applying Binary Search in an unsorted array is not possible. To apply Binary Search first the 2D array needs to be sorted in any order that itself takes (M*N)log(M*N) time.


2 Answers

Sometimes it's easier and always cleaner to put the search in a separate method:

 private Point find2DIndex(Object[][] array, Object search) {

    if (search == null || array == null) return null;

    for (int rowIndex = 0; rowIndex < array.length; rowIndex++ ) {
       Object[] row = array[rowIndex];
       if (row != null) {
          for (int columnIndex = 0; columnIndex < row.length; columnIndex++) {
             if (search.equals(row[columnIndex])) {
                 return new Point(rowIndex, columnIndex);
             }
          }
       }
    }
    return null; // value not found in array
 }

This will return the first match only. If you need all, collect all points in a List and return that list at the end.


Usage:

private void doSomething() {
  String[][] array = {{"one", "1"},{"two","2"}, {"three","3"}};
  Point index = find2DIndex(array, "two");

  // change one value at index
  if (index != null)
     array[index.x][index.y] = "TWO";

  // change everything in the whole row
  if (index != null) {
     String[] row = array[index.x];
     // change the values in that row
  }

}
like image 193
Andreas Dolk Avatar answered Oct 24 '22 15:10

Andreas Dolk


Updated due to your comment:

for(String[] subarray : array){
   int foundIndex = -1;
   for(int i = 0; i < subarray.length; i++){
      if(subarray[i].equals(searchString)){
         foundIndex = i;
         break;
      }
   } 
   if(foundIndex != -1){
      // change all values that are not at position foundIndex
      for(int i = 0; i < subarray.length; i++){
         if(i != foundIndex){
            subarray[i] = "something";
         }
      } 
      break;
   }
}
like image 33
morja Avatar answered Oct 24 '22 15:10

morja