For the lookup of ordered sequential tables we know that the most common is the binary or binary search strategy. The code is very concise, first glance:
int BinarySearch (vector<int> ins, int key)
{
int low = 0,high = Ins.size ()-1, mid;
while (low <= high)
{
mid = (low + high)/2;
if (ins[mid] = = key)
{
return mid;
}
else if (Ins[mid] > key)
{high
= mid-1;
}
else
{Low
= mid + 1;
}
}
return-1;
}
Looking at a very natural thinking process, I just don't know whether to ask a question: why high = mid-1, low = mid + 1. Is it possible to High = mid and Low = mid? is not more concise.
The answer is no.
If you do, you will not be able to find the last element. When the last 3 elements are left, mid can take the middle number, so that the number of Low,high points is adjacent to each other. When you calculate mid again, you can no longer jump to the high value because we know the effect of the next rounding in the computer. Therefore, the last value cannot be indexed. The middle is all yes, and the first one can. Why is it. Suppose you look for the first number, the last low point to the first, high to the second, and the next to mid, exactly where you can get the first number. Therefore, it is possible to find out.
See here, it seems conceivable that only low = mid + 1, then high two ways are OK, that is, high = mid, or High = mid is OK.
Yes, that's true. The same way as the analysis. The key is to see the low to have a step forward calculation, so as to achieve the highest number of positions. The high-level will be whatever it is good for. However, it is recommended that high = mid-1 and low = mid + 1.
Complete test code, want to actually verify, compile and run the test.
#include <iostream>
#include <vector>
using namespace std;
int BinarySearch (vector<int> ins, int key)
{
int low = 0,high = Ins.size ()-1, mid;
while (low <= high)
{
mid = (low + high)/2;
if (ins[mid] = = key)
{
return mid;
}
else if (Ins[mid] > key)
{high
= mid-1;
}
else
{Low
= mid + 1;
}
}
return-1;
}
int main ()
{
vector<int> ins;
int n;
CIN >> N;
for (int i = 0; i < n; i++)
{
int A;
Cin >> A;
Ins.push_back (a);
}
int key;
CIN >> Key;
cout << BinarySearch (ins,key) << Endl;
}