Explain what the following code does. What is its (worst-case) time complexity in terms of big O.

Assume below that when the method is called, n is the number of rows; and m is the number of columns.

public static boolean search(double[] data, int n, int m, double target) {

int i; // for the row index
int j; //for the column index
for (i = 0; i < n; i++) {
	for (j = 0; j < m;j++) {
		if (a[i][j] == target){
			return true;
		}
    	}
 }
return false;

}

Your code is searching for target value in 2D-Array.First it searches 1st row completely and if target value is not found then it proceeds to next row and so on.

If target value is found at any point of time it will return true from the method.

If target value is not found in array it will return false.

Worst Case O(nm).

2 Likes