VoyForums
[ Show ]
Support VoyForums
[ Shrink ]
VoyForums Announcement: Programming and providing support for this service has been a labor of love since 1997. We are one of the few services online who values our users' privacy, and have never sold your information. We have even fought hard to defend your privacy in legal cases; however, we've done it with almost no financial support -- paying out of pocket to continue providing the service. Due to the issues imposed on us by advertisers, we also stopped hosting most ads on the forums many years ago. We hope you appreciate our efforts.

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 ]


[ Next Thread | Previous Thread | Next Message | Previous Message ]

Date Posted: 21:16:02 12/05/01 Wed
Author: Richard In Texas
Subject: Binary Search SourceCode...

I just wrote a sample function of Binary search .. I don't know if there is any bugs... :)
==========================================================

#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;i array[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; i cout << 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);
}


[ Next Thread | Previous Thread | Next Message | Previous Message ]

Post a message:
This forum requires an account to post.
[ Create Account ]
[ Login ]
[ Contact Forum Admin ]


Forum timezone: GMT-6
VF Version: 3.00b, ConfDB:
Before posting please read our privacy policy.
VoyForums(tm) is a Free Service from Voyager Info-Systems.
Copyright © 1998-2019 Voyager Info-Systems. All Rights Reserved.