# Algorithm test question

• March 16th, 2013, 11:37
javapava
Algorithm test question
Here is the question: Given an array of 1000 elements in sorted order what is the
largest possible value that will be printed when the array is
passed to method mystery?

And here is the mystery code
Code :

```public int mystery(int[] v, int t) {   int w = 0; int h = v.length - 1; int c = 0; while(w <= h) {   c++; int m = (w + h) >>> 1; if(v[m] < t) {h = m - 1};   else if(v[m] > t) {w = m + 1};   else {   System.out.print(c);   return m; } }   System.out.print(c);   return -(w + 1); }```

Could someone explain it to me how this is 9? It would be greatly appreciated.
• March 16th, 2013, 12:00
Norm
Re: Algorithm test question
Please edit the code and properly format it. Its poor formatting makes it hard to read and understand.
Nested statements should be indented
Statements inside of if statement control should be enclosed in {}s
}s should not be in the same column.
• March 16th, 2013, 14:50
javapava
Re: Algorithm test question
Norm, I tried to make the code more easier to read and understandable. I tried working it out a few times, but I am still confused.
• March 16th, 2013, 15:08
Norm
Re: Algorithm test question
The formatting is different, but I can't say its formatting is better.
There are {}s on the same line with the if and else
There are }s one beneath the other.

To see what the code is doing, add some printlns to print out the values of the variables as they are changed and used.
• March 17th, 2013, 07:43
SiL3NTK0D3R
Re: Algorithm test question

Code :

```public static int mystery (int[] v, int t) {   int w = 0; int h = v.length - 1; int c = 0; while (w <= h) { c++; // 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 int m = (w + h) >>> 1; // 499 | 294 | 124 | 61 | 30 | 14 | 6 | 2 if (v [m] < t) // if v[499] < 1000 | if v[294] < 1000 | if v[124] < 1000 | if v[61] < 1000 | if v[30] < 1000 | if v[14] < 1000 | if v[6] < 1000 | if v[2] < 1000 { h = m - 1; // h = 499 - 1 = 498 | h = 249 - 1 = 248 | h = 124 - 1 = 123 | h = 61 - 1 = 60 | h = 30 - 1 = 29 | h = 14 - 1 = 13 | h = 6 - 1 = 5 | h = 2 - 1 = 1 }   else if (v [m] > t) { w = m + 1; }   else {   System.out.print (c);   return m; } }     System.out.print (c);   return -(w + 1); }```

Code with syntax highlighting:
http://s1.postimage.org/6kbqum9e5/Capture.png

9 is the total number of loops it does when the method is called. :)

*TIP*
Debugger is always helpful in this sort of problem
• March 17th, 2013, 16:48
Starstreak
Re: Algorithm test question
The code has some syntax errors.

If you test this class, try using t = -1 and see what value is printed out.