Note 100% certain I follow what you are trying to do.
But some points:
(a) C++ is almost space insensitive. The only areas you have to worry are in the middle of keywords e.g. cla ss A { } is not acceptable, nor in the middle of stuff like operator<< e.g. std::cout< <"Hello"<<std::endl;
(b) Consider your code:
if(first <= last)
{
int mid = (first + last) / 2;
}
This creates a variable mid. BUT mid has scope ONLY within the braces
e.g. only for ONE line of code. Therefore this if and the creation of mid is useless.
Then you try to use a mid LATER but that does't exist so you get errors.
(c) you pass values into your function e.g. first and last, but immediately you assign them to some value from your matrix. This negates the purpose of calling them into the function.
if(key == Values[][mid])
This line does not work since you have to define the first array index.
Please start with something a lot simpler, try just printing the array, then swapping it around. Doing stuff in stages is often quicker than doing the problem in hand.
StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
Actually, if you are doing a binary search, make 100% certain that you understand the algorithm in 1D. That is important since 2D array can be easily thougth of as a 1D array. The binary search can be done recursively
but let us start with the simple 1d binary search.
It REALLY helps to do this on paper with three coloured counters that you place on the number the index points to.
consider a set of numbers that are ordered, for simpicity consider
0-99. in linear order.
Now set target = 43 (anynumber between 0-99 will do)
set first =0
set last = 99
set mid = (first+last)/2 = 49 (remember integer arithmatic)
// Loop over
while(mid!=target)
{
if (mid>target) // obviously last>mid and it is also LOTs
last=mid; // bigger than target
else
first=mid;
mid=(first+last)/2
}
Understand how THIS works.
Now continue to see that if you have an ordered array of 100 points.
Then first,mid,last represent the array index and the values in the array are only used in the test to see if array[mid]>target.
This is only a fraction away from a 2D array, and slight modifications away from a recursive function.
StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138