/************************************************************************
-------------------------------------------
ALGORITHM FOR BINARY SEARCH
-------------------------------------------
1. set BEG = Lower Bound,END = Upper Bound & MID = int [(BEG + END)/2]
2. Repeat step 3 & 4 while BEG <= END & DATA[MID] != ITEM
3. if ITEM < DATA[MID]
set END = MID - 1
else,
set BEG = MID + 1
4. set MID = int [(BEG + END)/2]
3. if DATA[MID] = ITEM, then set LOC = MID
else, set LOC = NULL
6. Return
*************************************************************************/
#include "iostream.h"
#include "conio.h"
int main()
{
int ITEM,N,*DATA;
cout << "How many numbers? ";
cin >> N;
DATA = new int[N];
cout << "\nEnter Numbers : ";
for(int i = 0;i < N;i++)
cin >> DATA[i];
cout << "\nSearch : ";
cin >> ITEM;
int BEG,END,MID;
BEG = 0;
END = N - 1;
MID = int ((BEG + END) / 2);
while((BEG <= END) && (DATA[MID] != ITEM))
{
if(ITEM < DATA[MID])
END = MID - 1;
else
BEG = MID + 1;
MID = int ((BEG + END) / 2);
}
if(DATA[MID] == ITEM)
cout << "\nData Found : " << DATA[MID];
else
cout << "\nData Not Found";
getch();
return 0;
}
No comments:
Post a Comment