forked from sainirock61/CPP-Projects-Algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
68 lines (55 loc) · 1.81 KB
/
binarysearch.cpp
File metadata and controls
68 lines (55 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
using namespace std;
int main()
{
cout<<" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
cout<<" BINARY SEARCH \n";
cout<<" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
int n,i,num[500],a,flag,m;
cout<<"Enter the number of terms of array :--";
while(!(cin>>n)|| (n<0))
{
cin.clear();
cin.ignore(100,'\n');
cout<<"INVALID INPUT. ENTER AGAIN:";
}
cout<<"Enter the terms of Array : "<<endl;
for(i=0;i<n;i++)
{
cin>>num[i];
}
cout<<" ================================================================================\n";
cout<<"\n\nEnter the element you want to search :- ";
while(!(cin>>a)|| (a<0))
{
cin.clear();
cin.ignore(100,'\n');
cout<<" INVALID INPUT. ENTER AGAIN :-- ";
}
int first=0;
int last = n-1;
int middle =(first+last)/2;
cout<<"========================================================================================\n\n";
while(first<=last)
{
if (num[middle] < a)
{
first = middle + 1;
}
else if (num[middle] == a)
{
cout<< " Element Found at Location "<<middle+1<<"\n";
break;
}
else
{
last =middle-1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"\n\n NOT FOUND \n";
}
cout<<"\n========================================================================================\n\n";
}