-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBINARY SEARCH.cpp
More file actions
47 lines (44 loc) · 836 Bytes
/
BINARY SEARCH.cpp
File metadata and controls
47 lines (44 loc) · 836 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
//binary search
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
int i,n,num;
int *arr;
cout<<"---------CREATE AN ARRAY FIRST--------\n";
cout<<"Enter the size of the array\n";
cin>>n;
arr=(int *) malloc( n * sizeof(int) );
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the no. to be searched :\n";
cin>>num;
int low=0,high=n-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(arr[mid]<num)
{
low=mid+1;
}
else if(arr[mid]==num)
{
cout<<"Element "<<num<<" found at position "<<mid+1;
break;
}
else
{
high=mid-1;
}
}
if(low>high)
{
cout<<"Element"<<num<<"not found";
}
return 0;
}