Tuesday, November 22, 2011

Search in 2D array rowwise and columnwise sorted


public static void search(int x,int a[][])
  {
    int i=0;
    int j=a[0].length-1;
    while(i<a.length && j>=0) {
      if(a[i][j]==x){
        System.out.println(x + " is found at position [" + i + "," + j + "]");
        return;
      }
      if(a[i][j]>x)
        j--;
      else
        i++;
    }
    System.out.println("Element not found in the given matrix");
  }

No comments:

Post a Comment