Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
question background
Hello, I need to calculate my method's time-complexity for school, and they haven't given me the proper tools for it, sadly :(. I have tried googeling but I'm not comfortable enough to do it alone.

The Task
We have a 2-dimensional array that is sorted pretty much like this:
[41] [42] [43] [44] [45] [46] [47] [48] row 5
[33] [34] [35] [36] [37] [38] [39] [40] row 4
[25] [26] [27] [28] [29] [30] [31] [32] row 3
[17] [18] [19] [20] [21] [22] [23] [24] row 2
[9] [10] [11] [12] [13] [14] [15] [16] row 1
[1] [2] [3] [4] [5] [6] [7] [8] row 0

I need to write a method that will get this array as param, and an int val from the user and the method has to search it in the array in a time of no more than O(n).
That is the code I have written:

<pre>
int l = 0;
int r = m.length-1;  
        while (l <= r)
        {
            int middle = l + ((r-l)/2);
            if (m[middle][m[middle].length-1] == val)
                return true;
            if (m[middle][m[middle].length-1] < val)
                l = middle + 1;
            else
            {
                if (middle == 0) {
                    r = m[middle].length-1;
                    l = 0;
                    if (binarySearch(m, l, r, middle, val) == 0) return true;   
                }
                if (middle > 0)
                    if (m[middle-1][m[middle-1].length-1] < val) {
                        r = m[middle].length-1;
                        l = 0;
                        if (binarySearch(m, l, r, middle, val) == 0) return true;
                    }
                r = middle - 1;
            }
        }
return false
}

I start by checking the last column of the middle row of the array. If the value there is val, great.
If smaller, I won't waste my time on the former rows.
If the value is greater, I then check if the row before it(middle -1) has a last column value that is smaller than val. if yes, this means val can only be in the current row. So I proceed into a second binarySearch.
There is another test to check if middle is 0, that proceeds to another binarySearch. Without it, I get exception outOfBounds in my prior middle-1 check.

Basically I have a big BinarySearch method that if it finds a last column that is bigger than val, uses another BinarySearch.
Would you say that it is 2(log n)? n (log n)? I find it hard to call.
Thank you!

What I have tried:

Google, youtube, university book
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900