Show your support by donating any amount. (Note: We are still technically a for-profit company, so your
contribution is not tax-deductible.)
PayPal Acct:
Feedback:
Donate to VoyForums (PayPal):
[ Login ] [ Contact Forum Admin ] [ Main index ] [ Post a new message ] [ Search | Check update time ] |
#include
void Print(short[], short);
short BinSearch(short[],short num, short High, short Low = 0);
void main()
{
const short Cnt = 20; //you change the Value of Cnt
short array[Cnt];
short number, offset;
short i;
for(i=0;iarray[i] = i;
cout << "The content of the array\n";
Print(array,Cnt);
while(1)
{
cout << "Please input a number to be searched(-1 to exit) : ";
cin >> number;
if(number==-1) break;
//call BinSearch(array, number, High, 0)
if((offset=BinSearch(array, number, Cnt-1)) != -1)
cout << "The offset is " << offset << endl;
else
cout << "No " << number << " in the array!\n";
}
}
void Print(short array[], short Cnt)
{
for(short i=0; icout << array[i]<< " ";
cout << endl;
}
short BinSearch(short array[],short num, short High,short Low)
{
short mid;
if(Low > High)
return -1; //couldn't find it...
mid = (Low + High)/2;
if(array[mid] == num) //got it!!
return mid;
else if(array[mid] > num)
High = mid-1; //range becomes the first part
else if(array[mid] < num)
Low = mid + 1; //range becomes the last part
return BinSearch(array,num, High, Low);
}