-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
65 lines (61 loc) · 952 Bytes
/
BinarySearch.cpp
File metadata and controls
65 lines (61 loc) · 952 Bytes
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
#include<iostream>
using namespace std;
int bsearch(int arr[], int n, int x)
{
int left=0;
int right=n-1;
while(left<=right){
int mid=(right+left)/2;
if(arr[mid]==x)
{
return mid;
}
else if(arr[mid]>x)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
}
int main()
{
int num,myarr[1000],output,i,j,temp,n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>myarr[i];
}
for (i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if (myarr[i]>myarr[j])
{
temp=myarr[i];
myarr[i]=myarr[j];
myarr[j]=temp;
}
}
}
cout<<"The sorted array is : "<<endl;
for (i=0;i<n;i++)
{
cout<<myarr[i]<<" ";
}
cout<<endl;
cout<<"Enter the number that you want to search in the array : "<<endl;
cin>>num;
output=bsearch(myarr,n,num);
if(output==-1)
{
cout<<"Not found !"<<endl;
}
else
{
cout<<"Element found at position : "<<output<<endl;
}
return 0;
}