-1

I have this algorithm to search a sorted 2d Array where each row is in ascending order and each column is also in ascending order. what would the run time complexity be for this ?

public static boolean main1(int target,int size) {


    int a=1;
int matrix[][]=new int[size][size];    //Initialize and fill array

      for(int i=0;i<size;i++){
       for(int j=0;j<size;j++){
        matrix[i][j]=a;
        a++;
       }

   }


    if(matrix==null || matrix.length==0 || matrix[0].length==0) 
        return false;

    int m = matrix.length;
    int n = matrix[0].length;

    int start = 0;
    int end = m*n-1;

    while(start<=end){
        int mid=(start+end)/2;
        int midX=mid/n;
        int midY=mid%n;

        if(matrix[midX][midY]==target) 
            return true;

        if(matrix[midX][midY]<target){
            start=mid+1;
        }else{
            end=mid-1;
        }
    }

    return false;
}

}

user3443632
  • 17
  • 1
  • 6

1 Answers1

0

Your "2D array" of rows and columns in ascending order with dimensions size x size is a sorted array of size^2 elements. So O(log size).

mattm
  • 5,851
  • 11
  • 47
  • 77