-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbinary_search.cpp
55 lines (55 loc) · 1 KB
/
binary_search.cpp
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
#include<iostream>
using namespace std;
int main()
{
int n,a[100],x,mid=0,s=0,e=0;
cout<<"Enter size of array: ";
cin>>n;
cout<<"Enter elements of array: \n";
for(int i=0; i<n; i++)
{
cin>>a[i];
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n-i; j++)
{
if(a[j]>a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
cout<<"Sorted array: "<<endl;
for(int i=0; i<n; i++)
{
cout<<a[i]<<" "<<endl;
}
e = n-1;
cout<<"Enter a no to search: ";
cin>>x;
mid = (s+e)/2;
while(s<e && a[mid]!=x)
{
if(x>a[mid])
{
s = mid+1;
}
else
{
e = mid-1;
}
mid = (s+e)/2;
}
if(a[mid] == x)
{
cout<<"Element "<<a[mid]<<" found at "<<mid+1<<" position"<<endl;
}
else
{
cout<<"Element not found"<<endl;
}
return 0;
}